<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.2">
<title>Domain Model</title>
<link rel="stylesheet" href="./css/hibernate.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.js"></script>
<script>document.addEventListener('DOMContentLoaded', prettyPrint)</script>
</head>
<body class="article">
<div id="header">
</div>
<div id="content">
<div class="sect1">
<h2 id="domain-model">Domain Model</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The term <a href="https://en.wikipedia.org/wiki/Domain_model">domain model</a> comes from the realm of data modeling.
It is the model that ultimately describes the <a href="https://en.wikipedia.org/wiki/Problem_domain">problem domain</a> you are working in.
Sometimes you will also hear the term <em>persistent classes</em>.</p>
</div>
<div class="paragraph">
<p>Ultimately the application domain model is the central character in an ORM.
They make up the classes you wish to map. Hibernate works best if these classes follow the Plain Old Java Object (POJO) / JavaBean programming model.
However, none of these rules are hard requirements.
Indeed, Hibernate assumes very little about the nature of your persistent objects. You can express a domain model in other ways (using trees of <code>java.util.Map</code> instances, for example).</p>
</div>
<div class="paragraph">
<p>Historically applications using Hibernate would have used its proprietary XML mapping file format for this purpose.
With the coming of JPA, most of this information is now defined in a way that is portable across ORM/JPA providers using annotations (and/or standardized XML format).
This chapter will focus on JPA mapping where possible.
For Hibernate mapping features not supported by JPA we will prefer Hibernate extension annotations.</p>
</div>
<div class="sect2">
<h3 id="mapping-types">Mapping types</h3>
<div class="paragraph">
<p>Hibernate understands both the Java and JDBC representations of application data.
The ability to read/write this data from/to the database is the function of a Hibernate <em>type</em>.
A type, in this usage, is an implementation of the <code>org.hibernate.type.Type</code> interface.
This Hibernate type also describes various aspects of behavior of the Java type such as how to check for equality, how to clone values, etc.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="title">Usage of the word <em>type</em></div>
<div class="paragraph">
<p>The Hibernate type is neither a Java type nor a SQL data type.
It provides information about both of these as well as understanding marshalling between.</p>
</div>
<div class="paragraph">
<p>When you encounter the term type in discussions of Hibernate, it may refer to the Java type, the JDBC type, or the Hibernate type, depending on context.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To help understand the type categorizations, let&#8217;s look at a simple table and domain model that we wish to map.</p>
</div>
<div id="mapping-types-basic-example" class="exampleblock">
<div class="title">Example 1. Simple table and domain model</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">create table Contact (
    id integer not null,
    first varchar(255),
    last varchar(255),
    middle varchar(255),
    notes varchar(255),
    starred boolean not null,
    website varchar(255),
    primary key (id)
)</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Contact")
public static class Contact {

    @Id
    private Integer id;

    private Name name;

    private String notes;

    private URL website;

    private boolean starred;

    //Getters and setters are omitted for brevity
}

@Embeddable
public class Name {

    private String first;

    private String middle;

    private String last;

    // getters and setters omitted
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In the broadest sense, Hibernate categorizes types into two groups:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#categorization-value">Value types</a></p>
</li>
<li>
<p><a href="#categorization-entity">Entity types</a></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="categorization-value">Value types</h4>
<div class="paragraph">
<p>A value type is a piece of data that does not define its own lifecycle.
It is, in effect, owned by an entity, which defines its lifecycle.</p>
</div>
<div class="paragraph">
<p>Looked at another way, all the state of an entity is made up entirely of value types.
These state fields or JavaBean properties are termed <em>persistent attributes</em>.
The persistent attributes of the <code>Contact</code> class are value types.</p>
</div>
<div class="paragraph">
<p>Value types are further classified into three sub-categories:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Basic types</dt>
<dd>
<p>in mapping the <code>Contact</code> table, all attributes except for name would be basic types. Basic types are discussed in detail in <a href="chapters/domain/basic_types.html#basic"><em>Basic Types</em></a></p>
</dd>
<dt class="hdlist1">Embeddable types</dt>
<dd>
<p>the name attribute is an example of an embeddable type, which is discussed in details in <a href="chapters/domain/embeddables.html#embeddables"><em>Embeddable Types</em></a></p>
</dd>
<dt class="hdlist1">Collection types</dt>
<dd>
<p>although not featured in the aforementioned example, collection types are also a distinct category among value types. Collection types are further discussed in <a href="chapters/domain/collections.html#collections"><em>Collections</em></a></p>
</dd>
</dl>
</div>
</div>
<div class="sect3">
<h4 id="categorization-entity">Entity types</h4>
<div class="paragraph">
<p>Entities, by nature of their unique identifier, exist independently of other objects whereas values do not.
Entities are domain model classes which correlate to rows in a database table, using a unique identifier.
Because of the requirement for a unique identifier, entities exist independently and define their own lifecycle.
The <code>Contact</code> class itself would be an example of an entity.</p>
</div>
<div class="paragraph">
<p>Mapping entities is discussed in detail in <a href="chapters/domain/entity.html#entity"><em>Entity</em></a>.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="naming">Naming strategies</h3>
<div class="paragraph">
<p>Part of the mapping of an object model to the relational database is
mapping names from the object model to the corresponding database names.
Hibernate looks at this as 2 stage process:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The first stage is determining a proper logical name from the domain model mapping.  A
logical name can be either explicitly specified by the user (using <code>@Column</code> or
<code>@Table</code> e.g.) or it can be implicitly determined by Hibernate through an
<a href="#ImplicitNamingStrategy">ImplicitNamingStrategy</a> contract.</p>
</li>
<li>
<p>Second is the resolving of this logical name to a physical name which is defined
by the <a href="#PhysicalNamingStrategy">PhysicalNamingStrategy</a> contract.</p>
</li>
</ul>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="title">Historical NamingStrategy contract</div>
<div class="paragraph">
<p>Historically Hibernate defined just a single <code>org.hibernate.cfg.NamingStrategy</code>.  That singular
NamingStrategy contract actually combined the separate concerns that are now modeled individually
as ImplicitNamingStrategy and PhysicalNamingStrategy.</p>
</div>
<div class="paragraph">
<p>Also, the NamingStrategy contract was often not flexible enough to properly apply a given naming
"rule", either because the API lacked the information to decide or because the API was honestly
not well defined as it grew.</p>
</div>
<div class="paragraph">
<p>Due to these limitation, <code>org.hibernate.cfg.NamingStrategy</code> has been deprecated and then removed
in favor of ImplicitNamingStrategy and PhysicalNamingStrategy.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>At the core, the idea behind each naming strategy is to minimize the amount of
repetitive information a developer must provide for mapping a domain model.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="title">JPA Compatibility</div>
<div class="paragraph">
<p>JPA defines inherent rules about implicit logical name determination.  If JPA provider
portability is a major concern, or if you really just like the JPA-defined implicit
naming rules, be sure to stick with ImplicitNamingStrategyJpaCompliantImpl (the default)</p>
</div>
<div class="paragraph">
<p>Also, JPA defines no separation between logical and physical name.  Following the JPA
specification, the logical name <strong>is</strong> the physical name.  If JPA provider portability
is important, applications should prefer not to specify a PhysicalNamingStrategy.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="ImplicitNamingStrategy">ImplicitNamingStrategy</h4>
<div class="paragraph">
<p>When an entity does not explicitly name the database table that it maps to, we need
to implicitly determine that table name.  Or when a particular attribute does not explicitly name
the database column that it maps to, we need to implicitly determine that column name.  There are
examples of the role of the <code>org.hibernate.boot.model.naming.ImplicitNamingStrategy</code> contract to
determine a logical name when the mapping did not provide an explicit name.</p>
</div>
<div class="paragraph">
<p><span class="image"><img src="images/domain/naming/implicit_naming_strategy_diagram.svg" alt="Implicit Naming Strategy Diagram"></span></p>
</div>
<div class="paragraph">
<p>Hibernate defines multiple ImplicitNamingStrategy implementations out-of-the-box.  Applications
are also free to plug-in custom implementations.</p>
</div>
<div class="paragraph">
<p>There are multiple ways to specify the ImplicitNamingStrategy to use.  First, applications can specify
the implementation using the <code>hibernate.implicit_naming_strategy</code> configuration setting which accepts:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>pre-defined "short names" for the out-of-the-box implementations</p>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>default</code></dt>
<dd>
<p>for <code>org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl</code> - an alias for <code>jpa</code></p>
</dd>
<dt class="hdlist1"><code>jpa</code></dt>
<dd>
<p>for <code>org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl</code> - the JPA 2.0 compliant naming strategy</p>
</dd>
<dt class="hdlist1"><code>legacy-hbm</code></dt>
<dd>
<p>for <code>org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl</code> - compliant with the original Hibernate NamingStrategy</p>
</dd>
<dt class="hdlist1"><code>legacy-jpa</code></dt>
<dd>
<p>for <code>org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl</code> - compliant with the legacy NamingStrategy developed for JPA 1.0, which was unfortunately unclear in many respects regarding implicit naming rules</p>
</dd>
<dt class="hdlist1"><code>component-path</code></dt>
<dd>
<p>for <code>org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl</code> - mostly follows <code>ImplicitNamingStrategyJpaCompliantImpl</code> rules, except that it uses the full composite paths, as opposed to just the ending property part</p>
</dd>
</dl>
</div>
</li>
<li>
<p>reference to a Class that implements the <code>org.hibernate.boot.model.naming.ImplicitNamingStrategy</code> contract</p>
</li>
<li>
<p>FQN of a class that implements the <code>org.hibernate.boot.model.naming.ImplicitNamingStrategy</code> contract</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Secondly, applications and integrations can leverage <code>org.hibernate.boot.MetadataBuilder#applyImplicitNamingStrategy</code>
to specify the ImplicitNamingStrategy to use.  See
<a href="chapters/bootstrap/Bootstrap.html#bootstrap">Bootstrap</a> for additional details on bootstrapping.</p>
</div>
</div>
<div class="sect3">
<h4 id="PhysicalNamingStrategy">PhysicalNamingStrategy</h4>
<div class="paragraph">
<p>Many organizations define rules around the naming of database objects (tables, columns, foreign-keys, etc).
The idea of a PhysicalNamingStrategy is to help implement such naming rules without having to hard-code them
into the mapping via explicit names.</p>
</div>
<div class="paragraph">
<p>While the purpose of an ImplicitNamingStrategy is to determine that an attribute named <code>accountNumber</code> maps to
a logical column name of <code>accountNumber</code> when not explicitly specified, the purpose of a PhysicalNamingStrategy
would be, for example, to say that the physical column name should instead be abbreviated <code>acct_num</code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>It is true that the resolution to <code>acct_num</code> could have been handled in an ImplicitNamingStrategy in this case.
But the point is separation of concerns.  The PhysicalNamingStrategy will be applied regardless of whether
the attribute explicitly specified the column name or whether we determined that implicitly.  The
ImplicitNamingStrategy would only be applied if an explicit name was not given.  So it depends on needs
and intent.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default implementation is to simply use the logical name as the physical name.  However
applications and integrations can define custom implementations of this PhysicalNamingStrategy
contract.  Here is an example PhysicalNamingStrategy for a fictitious company named Acme Corp
whose naming standards are to:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>prefer underscore-delimited words rather than camel-casing</p>
</li>
<li>
<p>replace certain words with standard abbreviations</p>
</li>
</ul>
</div>
<div class="exampleblock">
<div class="title">Example 2. Example PhysicalNamingStrategy implementation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or &lt;http://www.gnu.org/licenses/lgpl-2.1.html&gt;.
 */
package org.hibernate.userguide.naming;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;

import org.apache.commons.lang3.StringUtils;

/**
 * An example PhysicalNamingStrategy that implements database object naming standards
 * for our fictitious company Acme Corp.
 * &lt;p/&gt;
 * In general Acme Corp prefers underscore-delimited words rather than camel casing.
 * &lt;p/&gt;
 * Additionally standards call for the replacement of certain words with abbreviations.
 *
 * @author Steve Ebersole
 */
public class AcmeCorpPhysicalNamingStrategy implements PhysicalNamingStrategy {
	private static final Map&lt;String,String&gt; ABBREVIATIONS = buildAbbreviationMap();

	@Override
	public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		// Acme naming standards do not apply to catalog names
		return name;
	}

	@Override
	public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		// Acme naming standards do not apply to schema names
		return null;
	}

	@Override
	public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		final List&lt;String&gt; parts = splitAndReplace( name.getText() );
		return jdbcEnvironment.getIdentifierHelper().toIdentifier(
				join( parts ),
				name.isQuoted()
		);
	}

	@Override
	public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		final LinkedList&lt;String&gt; parts = splitAndReplace( name.getText() );
		// Acme Corp says all sequences should end with _seq
		if ( !"seq".equalsIgnoreCase( parts.getLast() ) ) {
			parts.add( "seq" );
		}
		return jdbcEnvironment.getIdentifierHelper().toIdentifier(
				join( parts ),
				name.isQuoted()
		);
	}

	@Override
	public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment) {
		final List&lt;String&gt; parts = splitAndReplace( name.getText() );
		return jdbcEnvironment.getIdentifierHelper().toIdentifier(
				join( parts ),
				name.isQuoted()
		);
	}

	private static Map&lt;String, String&gt; buildAbbreviationMap() {
		TreeMap&lt;String,String&gt; abbreviationMap = new TreeMap&lt;&gt; ( String.CASE_INSENSITIVE_ORDER );
		abbreviationMap.put( "account", "acct" );
		abbreviationMap.put( "number", "num" );
		return abbreviationMap;
	}

	private LinkedList&lt;String&gt; splitAndReplace(String name) {
		LinkedList&lt;String&gt; result = new LinkedList&lt;&gt;();
		for ( String part : StringUtils.splitByCharacterTypeCamelCase( name ) ) {
			if ( part == null || part.trim().isEmpty() ) {
				// skip null and space
				continue;
			}
			part = applyAbbreviationReplacement( part );
			result.add( part.toLowerCase( Locale.ROOT ) );
		}
		return result;
	}

	private String applyAbbreviationReplacement(String word) {
		if ( ABBREVIATIONS.containsKey( word ) ) {
			return ABBREVIATIONS.get( word );
		}

		return word;
	}

	private String join(List&lt;String&gt; parts) {
		boolean firstPass = true;
		String separator = "";
		StringBuilder joined = new StringBuilder();
		for ( String part : parts ) {
			joined.append( separator ).append( part );
			if ( firstPass ) {
				firstPass = false;
				separator = "_";
			}
		}
		return joined.toString();
	}
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>There are multiple ways to specify the PhysicalNamingStrategy to use.  First, applications can specify
the implementation using the <code>hibernate.physical_naming_strategy</code> configuration setting which accepts:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>reference to a Class that implements the <code>org.hibernate.boot.model.naming.PhysicalNamingStrategy</code> contract</p>
</li>
<li>
<p>FQN of a class that implements the <code>org.hibernate.boot.model.naming.PhysicalNamingStrategy</code> contract</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Secondly, applications and integrations can leverage <code>org.hibernate.boot.MetadataBuilder#applyPhysicalNamingStrategy</code>.
See <a href="chapters/bootstrap/Bootstrap.html#bootstrap">Bootstrap</a> for additional details on bootstrapping.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="basic">Basic Types</h3>
<div class="paragraph">
<p>Basic value types usually map a single database column, to a single, non-aggregated Java type.
Hibernate provides a number of built-in basic types, which follow the natural mappings recommended by the JDBC specifications.</p>
</div>
<div class="paragraph">
<p>Internally Hibernate uses a registry of basic types when it needs to resolve a specific <code>org.hibernate.type.Type</code>.</p>
</div>
<div class="sect3">
<h4 id="basic-provided">Hibernate-provided BasicTypes</h4>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 1. Standard BasicTypes</caption>
<colgroup>
<col style="width: %;">
<col style="width: %;">
<col style="width: %;">
<col style="width: %;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Hibernate type (org.hibernate.type package)</th>
<th class="tableblock halign-left valign-top">JDBC type</th>
<th class="tableblock halign-left valign-top">Java type</th>
<th class="tableblock halign-left valign-top">BasicTypeRegistry key(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">StringType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">string, java.lang.String</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">MaterializedClob</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">CLOB</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">materialized_clob</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">TextType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">LONGVARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">text</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CharacterType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">CHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">char, java.lang.Character</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">char, java.lang.Character</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">BooleanType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">BIT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">boolean, java.lang.Boolean</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">boolean, java.lang.Boolean</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">NumericBooleanType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">INTEGER, 0 is false, 1 is true</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">boolean, java.lang.Boolean</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">numeric_boolean</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">YesNoType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">CHAR, 'N'/'n' is false, 'Y'/'y' is true. The uppercase value is written to the database.</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">boolean, java.lang.Boolean</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">yes_no</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">TrueFalseType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">CHAR, 'F'/'f' is false, 'T'/'t' is true. The uppercase value is written to the database.</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">boolean, java.lang.Boolean</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">true_false</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ByteType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TINYINT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">byte, java.lang.Byte</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">byte, java.lang.Byte</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ShortType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">SMALLINT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">short, java.lang.Short</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">short, java.lang.Short</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">IntegerTypes</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">INTEGER</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">int, java.lang.Integer</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">int, java.lang.Integer</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">LongType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">BIGINT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">long, java.lang.Long</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">long, java.lang.Long</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">FloatType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">FLOAT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">float, java.lang.Float</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">float, java.lang.Float</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DoubleType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">DOUBLE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">double, java.lang.Double</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">double, java.lang.Double</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">BigIntegerType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">NUMERIC</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.math.BigInteger</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">big_integer, java.math.BigInteger</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">BigDecimalType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">NUMERIC</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.math.BigDecimal</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">big_decimal, java.math.bigDecimal</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">TimestampType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIMESTAMP</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.sql.Timestamp</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">timestamp, java.sql.Timestamp</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">TimeType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIME</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.sql.Time</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">time, java.sql.Time</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DateType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">DATE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.sql.Date</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">date, java.sql.Date</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CalendarType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIMESTAMP</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.Calendar</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">calendar, java.util.Calendar</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CalendarDateType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">DATE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.Calendar</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">calendar_date</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CalendarTimeType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIME</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.Calendar</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">calendar_time</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CurrencyType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.Currency</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">currency, java.util.Currency</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">LocaleType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.Locale</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">locale, java.utility.locale</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">TimeZoneType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARCHAR, using the TimeZone ID</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.TimeZone</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">timezone, java.util.TimeZone</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">UrlType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.net.URL</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">url, java.net.URL</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ClassType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARCHAR (class FQN)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.Class</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">class, java.lang.Class</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">BlobType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">BLOB</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.sql.Blob</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">blob, java.sql.Blob</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ClobType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">CLOB</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.sql.Clob</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">clob, java.sql.Clob</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">BinaryType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARBINARY</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">byte[]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">binary, byte[]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">MaterializedBlobType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">BLOB</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">byte[]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">materialized_blob</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ImageType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">LONGVARBINARY</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">byte[]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">image</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">WrapperBinaryType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARBINARY</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.Byte[]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">wrapper-binary, Byte[], java.lang.Byte[]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CharArrayType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">char[]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">characters, char[]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CharacterArrayType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.Character[]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">wrapper-characters, Character[], java.lang.Character[]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">UUIDBinaryType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">BINARY</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.UUID</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">uuid-binary, java.util.UUID</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">UUIDCharType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">CHAR, can also read VARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.UUID</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">uuid-char</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PostgresUUIDType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">PostgreSQL UUID, through Types#OTHER, which complies to the PostgreSQL JDBC driver definition</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.util.UUID</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">pg-uuid</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">SerializableType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">VARBINARY</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">implementors of java.lang.Serializable</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Unlike the other value types, multiple instances of this type are registered. It is registered once under java.io.Serializable, and registered under the specific java.io.Serializable implementation class names.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">StringNVarcharType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">NVARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">nstring</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">NTextType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">LONGNVARCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">ntext</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">NClobType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">NCLOB</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.sql.NClob</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">nclob, java.sql.NClob</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">MaterializedNClobType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">NCLOB</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">materialized_nclob</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PrimitiveCharacterArrayNClobType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">NCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">char[]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">N/A</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CharacterNCharType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">NCHAR</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.Character</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">ncharacter</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">CharacterArrayNClobType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">NCLOB</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.lang.Character[]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">N/A</p></td>
</tr>
</tbody>
</table>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 2. Java 8 BasicTypes</caption>
<colgroup>
<col style="width: %;">
<col style="width: %;">
<col style="width: %;">
<col style="width: %;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Hibernate type (org.hibernate.type package)</th>
<th class="tableblock halign-left valign-top">JDBC type</th>
<th class="tableblock halign-left valign-top">Java type</th>
<th class="tableblock halign-left valign-top">BasicTypeRegistry key(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DurationType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">BIGINT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.time.Duration</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Duration, java.time.Duration</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">InstantType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIMESTAMP</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.time.Instant</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Instant, java.time.Instant</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">LocalDateTimeType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIMESTAMP</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.time.LocalDateTime</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">LocalDateTime, java.time.LocalDateTime</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">LocalDateType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">DATE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.time.LocalDate</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">LocalDate, java.time.LocalDate</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">LocalTimeType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIME</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.time.LocalTime</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">LocalTime, java.time.LocalTime</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">OffsetDateTimeType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIMESTAMP</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.time.OffsetDateTime</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">OffsetDateTime, java.time.OffsetDateTime</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">OffsetTimeType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIME</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.time.OffsetTime</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">OffsetTime, java.time.OffsetTime</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">OffsetTimeType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">TIMESTAMP</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">java.time.ZonedDateTime</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">ZonedDateTime, java.time.ZonedDateTime</p></td>
</tr>
</tbody>
</table>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 3. Hibernate Spatial BasicTypes</caption>
<colgroup>
<col style="width: %;">
<col style="width: %;">
<col style="width: %;">
<col style="width: %;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Hibernate type (org.hibernate.spatial package)</th>
<th class="tableblock halign-left valign-top">JDBC type</th>
<th class="tableblock halign-left valign-top">Java type</th>
<th class="tableblock halign-left valign-top">BasicTypeRegistry key(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">JTSGeometryType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">depends on the dialect</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">com.vividsolutions.jts.geom.Geometry</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">jts_geometry, or the classname of Geometry or any of its subclasses</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GeolatteGeometryType</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">depends on the dialect</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">org.geolatte.geom.Geometry</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">geolatte_geometry, or the classname of Geometry or any of its subclasses</p></td>
</tr>
</tbody>
</table>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>To use these hibernate-spatial types, you must add the <code>hibernate-spatial</code> dependency to your classpath <em>and</em> use a <code>org.hibernate.spatial.SpatialDialect</code> implementation.
See <a href="#spatial">[spatial]</a> for more details about spatial types.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>These mappings are managed by a service inside Hibernate called the <code>org.hibernate.type.BasicTypeRegistry</code>, which essentially maintains a map of <code>org.hibernate.type.BasicType</code> (a <code>org.hibernate.type.Type</code> specialization) instances keyed by a name.
That is the purpose of the "BasicTypeRegistry key(s)" column in the previous tables.</p>
</div>
</div>
<div class="sect3">
<h4 id="basic-annotation">The <code>@Basic</code> annotation</h4>
<div class="paragraph">
<p>Strictly speaking, a basic type is denoted by the <code>javax.persistence.Basic</code> annotation.
Generally speaking, the <code>@Basic</code> annotation can be ignored, as it is assumed by default.
Both of the following examples are ultimately the same.</p>
</div>
<div id="basic-annotation-explicit-example" class="exampleblock">
<div class="title">Example 3. <code>@Basic</code> declared explicitly</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public class Product {

    @Id
    @Basic
    private Integer id;

    @Basic
    private String sku;

    @Basic
    private String name;

    @Basic
    private String description;
}</code></pre>
</div>
</div>
</div>
</div>
<div id="basic-annotation-implicit-example" class="exampleblock">
<div class="title">Example 4. <code>@Basic</code> being implicitly implied</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public class Product {

    @Id
    private Integer id;

    private String sku;

    private String name;

    private String description;
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The JPA specification strictly limits the Java types that can be marked as basic to the following listing:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Java primitive types (<code>boolean</code>, <code>int</code>, etc)</p>
</li>
<li>
<p>wrappers for the primitive types (<code>java.lang.Boolean</code>, <code>java.lang.Integer</code>, etc)</p>
</li>
<li>
<p><code>java.lang.String</code></p>
</li>
<li>
<p><code>java.math.BigInteger</code></p>
</li>
<li>
<p><code>java.math.BigDecimal</code></p>
</li>
<li>
<p><code>java.util.Date</code></p>
</li>
<li>
<p><code>java.util.Calendar</code></p>
</li>
<li>
<p><code>java.sql.Date</code></p>
</li>
<li>
<p><code>java.sql.Time</code></p>
</li>
<li>
<p><code>java.sql.Timestamp</code></p>
</li>
<li>
<p><code>byte[]</code> or <code>Byte[]</code></p>
</li>
<li>
<p><code>char[]</code> or <code>Character[]</code></p>
</li>
<li>
<p><code>enums</code></p>
</li>
<li>
<p>any other type that implements <code>Serializable</code> (JPA&#8217;s "support" for <code>Serializable</code> types is to directly serialize their state to the database).</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>If provider portability is a concern, you should stick to just these basic types.
Note that JPA 2.1 did add the notion of a <code>javax.persistence.AttributeConverter</code> to help alleviate some of these concerns; see <a href="#basic-jpa-convert">JPA 2.1 AttributeConverters</a> for more on this topic.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The <code>@Basic</code> annotation defines 2 attributes.</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>optional</code> - boolean (defaults to true)</dt>
<dd>
<p>Defines whether this attribute allows nulls.
JPA defines this as "a hint", which essentially means that it effect is specifically required.
As long as the type is not primitive, Hibernate takes this to mean that the underlying column should be <code>NULLABLE</code>.</p>
</dd>
<dt class="hdlist1"><code>fetch</code> - FetchType (defaults to EAGER)</dt>
<dd>
<p>Defines whether this attribute should be fetched eagerly or lazily.
JPA says that EAGER is a requirement to the provider (Hibernate) that the value should be fetched when the owner is fetched, while LAZY is merely a hint that the value be fetched when the attribute is accessed.
Hibernate ignores this setting for basic types unless you are using bytecode enhancement.
See the <a href="chapters/pc/BytecodeEnhancement.html#BytecodeEnhancement">BytecodeEnhancement</a> for additional information on fetching and on bytecode enhancement.</p>
</dd>
</dl>
</div>
</div>
<div class="sect3">
<h4 id="basic-column-annotation">The <code>@Column</code> annotation</h4>
<div class="paragraph">
<p>JPA defines rules for implicitly determining the name of tables and columns.
For a detailed discussion of implicit naming see <a href="chapters/domain/naming.html#naming">Naming</a>.</p>
</div>
<div class="paragraph">
<p>For basic type attributes, the implicit naming rule is that the column name is the same as the attribute name.
If that implicit naming rule does not meet your requirements, you can explicitly tell Hibernate (and other providers) the column name to use.</p>
</div>
<div id="basic-annotation-explicit-column-example" class="exampleblock">
<div class="title">Example 5. Explicit column naming</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public class Product {

    @Id
    private Integer id;

    private String sku;

    private String name;

    @Column( name = "NOTES" )
    private String description;
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Here we use <code>@Column</code> to explicitly map the <code>description</code> attribute to the <code>NOTES</code> column, as opposed to the implicit column name <code>description</code>.</p>
</div>
<div class="paragraph">
<p>The <code>@Column</code> annotation defines other mapping information as well. See its Javadocs for details.</p>
</div>
</div>
<div class="sect3">
<h4 id="basic-registry">BasicTypeRegistry</h4>
<div class="paragraph">
<p>We said before that a Hibernate type is not a Java type, nor a SQL type, but that it understands both and performs the marshalling between them.
But looking at the basic type mappings from the previous examples,
how did Hibernate know to use its <code>org.hibernate.type.StringType</code> for mapping for <code>java.lang.String</code> attributes,
or its <code>org.hibernate.type.IntegerType</code> for mapping <code>java.lang.Integer</code> attributes?</p>
</div>
<div class="paragraph">
<p>The answer lies in a service inside Hibernate called the <code>org.hibernate.type.BasicTypeRegistry</code>, which essentially maintains a map of <code>org.hibernate.type.BasicType</code> (a <code>org.hibernate.type.Type</code> specialization) instances keyed by a name.</p>
</div>
<div class="paragraph">
<p>We will see later, in the <a href="#basic-type-annotation">Explicit BasicTypes</a> section, that we can explicitly tell Hibernate which BasicType to use for a particular attribute.
But first let&#8217;s explore how implicit resolution works and how applications can adjust implicit resolution.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>A thorough discussion of the <code>BasicTypeRegistry</code> and all the different ways to contribute types to it is beyond the scope of this documentation.
Please see Integrations Guide for complete details.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>As an example, take a String attribute such as we saw before with Product#sku.
Since there was no explicit type mapping, Hibernate looks to the <code>BasicTypeRegistry</code> to find the registered mapping for <code>java.lang.String</code>.
This goes back to the "BasicTypeRegistry key(s)" column we saw in the tables at the start of this chapter.</p>
</div>
<div class="paragraph">
<p>As a baseline within <code>BasicTypeRegistry</code>, Hibernate follows the recommended mappings of JDBC for Java types.
JDBC recommends mapping Strings to VARCHAR, which is the exact mapping that <code>StringType</code> handles.
So that is the baseline mapping within <code>BasicTypeRegistry</code> for Strings.</p>
</div>
<div class="paragraph">
<p>Applications can also extend (add new <code>BasicType</code> registrations) or override (replace an existing <code>BasicType</code> registration) using one of the
<code>MetadataBuilder#applyBasicType</code> methods or the <code>MetadataBuilder#applyTypes</code> method during bootstrap.
For more details, see <a href="#basic-custom-type">Custom BasicTypes</a> section.</p>
</div>
</div>
<div class="sect3">
<h4 id="basic-type-annotation">Explicit BasicTypes</h4>
<div class="paragraph">
<p>Sometimes you want a particular attribute to be handled differently.
Occasionally Hibernate will implicitly pick a <code>BasicType</code> that you do not want (and for some reason you do not want to adjust the <code>BasicTypeRegistry</code>).</p>
</div>
<div class="paragraph">
<p>In these cases you must explicitly tell Hibernate the <code>BasicType</code> to use, via the <code>org.hibernate.annotations.Type</code> annotation.</p>
</div>
<div id="basic-type-annotation-example" class="exampleblock">
<div class="title">Example 6. Using <code>@org.hibernate.annotations.Type</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public class Product {

    @Id
    private Integer id;

    private String sku;

    @org.hibernate.annotations.Type( type = "nstring" )
    private String name;

    @org.hibernate.annotations.Type( type = "materialized_nclob" )
    private String description;
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This tells Hibernate to store the Strings as nationalized data.
This is just for illustration purposes; for better ways to indicate nationalized character data see <a href="#basic-nationalized">Mapping Nationalized Character Data</a> section.</p>
</div>
<div class="paragraph">
<p>Additionally, the description is to be handled as a LOB. Again, for better ways to indicate LOBs see <a href="#basic-lob">Mapping LOBs</a> section.</p>
</div>
<div class="paragraph">
<p>The <code>org.hibernate.annotations.Type#type</code> attribute can name any of the following:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Fully qualified name of any <code>org.hibernate.type.Type</code> implementation</p>
</li>
<li>
<p>Any key registered with <code>BasicTypeRegistry</code></p>
</li>
<li>
<p>The name of any known <em>type definitions</em></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="basic-custom-type">Custom BasicTypes</h4>
<div class="paragraph">
<p>Hibernate makes it relatively easy for developers to create their own basic type mappings type.
For example, you might want to persist properties of type <code>java.util.BigInteger</code> to <code>VARCHAR</code> columns, or support completely new types.</p>
</div>
<div class="paragraph">
<p>There are two approaches to developing a custom type:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>implementing a <code>BasicType</code> and registering it</p>
</li>
<li>
<p>implementing a <code>UserType</code> which doesn&#8217;t require type registration</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>As a means of illustrating the different approaches, let&#8217;s consider a use case where we need to support a <code>java.util.BitSet</code> mapping that&#8217;s stored as a VARCHAR.</p>
</div>
<div class="sect4">
<h5 id="basic-custom-type-BasicType">Implementing a <code>BasicType</code></h5>
<div class="paragraph">
<p>The first approach is to directly implement the <code>BasicType</code> interface.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Because the <code>BasicType</code> interface has a lot of methods to implement, it&#8217;s much more convenient to extend the <code>AbstractStandardBasicType</code>,
or the <code>AbstractSingleColumnStandardBasicType</code> if the value is stored in a single database column.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>First, we need to extend the <code>AbstractSingleColumnStandardBasicType</code> like this:</p>
</div>
<div id="basic-custom-type-BitSetType-example" class="exampleblock">
<div class="title">Example 7. Custom <code>BasicType</code> implementation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public class BitSetType
        extends AbstractSingleColumnStandardBasicType&lt;BitSet&gt;
        implements DiscriminatorType&lt;BitSet&gt; {

    public static final BitSetType INSTANCE = new BitSetType();

    public BitSetType() {
        super( VarcharTypeDescriptor.INSTANCE, BitSetTypeDescriptor.INSTANCE );
    }

    @Override
    public BitSet stringToObject(String xml) throws Exception {
        return fromString( xml );
    }

    @Override
    public String objectToSQLString(BitSet value, Dialect dialect) throws Exception {
        return toString( value );
    }

    @Override
    public String getName() {
        return "bitset";
    }

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>AbstractSingleColumnStandardBasicType</code> requires an <code>sqlTypeDescriptor</code> and a <code>javaTypeDescriptor</code>.
The <code>sqlTypeDescriptor</code> is <code>VarcharTypeDescriptor.INSTANCE</code> because the database column is a VARCHAR.
On the Java side, we need to use a <code>BitSetTypeDescriptor</code> instance which can be implemented like this:</p>
</div>
<div id="basic-custom-type-BitSetTypeDescriptor-example" class="exampleblock">
<div class="title">Example 8. Custom <code>AbstractTypeDescriptor</code> implementation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public class BitSetTypeDescriptor extends AbstractTypeDescriptor&lt;BitSet&gt; {

    private static final String DELIMITER = ",";

    public static final BitSetTypeDescriptor INSTANCE = new BitSetTypeDescriptor();

    public BitSetTypeDescriptor() {
        super( BitSet.class );
    }

    @Override
    public String toString(BitSet value) {
        StringBuilder builder = new StringBuilder();
        for ( long token : value.toLongArray() ) {
            if ( builder.length() &gt; 0 ) {
                builder.append( DELIMITER );
            }
            builder.append( Long.toString( token, 2 ) );
        }
        return builder.toString();
    }

    @Override
    public BitSet fromString(String string) {
        if ( string == null || string.isEmpty() ) {
            return null;
        }
        String[] tokens = string.split( DELIMITER );
        long[] values = new long[tokens.length];

        for ( int i = 0; i &lt; tokens.length; i++ ) {
            values[i] = Long.valueOf( tokens[i], 2 );
        }
        return BitSet.valueOf( values );
    }

    @SuppressWarnings({"unchecked"})
    public &lt;X&gt; X unwrap(BitSet value, Class&lt;X&gt; type, WrapperOptions options) {
        if ( value == null ) {
            return null;
        }
        if ( BitSet.class.isAssignableFrom( type ) ) {
            return (X) value;
        }
        if ( String.class.isAssignableFrom( type ) ) {
            return (X) toString( value);
        }
        throw unknownUnwrap( type );
    }

    public &lt;X&gt; BitSet wrap(X value, WrapperOptions options) {
        if ( value == null ) {
            return null;
        }
        if ( String.class.isInstance( value ) ) {
            return fromString( (String) value );
        }
        if ( BitSet.class.isInstance( value ) ) {
            return (BitSet) value;
        }
        throw unknownWrap( value.getClass() );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>unwrap</code> method is used when passing a <code>BitSet</code> as a <code>PreparedStatement</code> bind parameter, while the <code>wrap</code> method is used to transform the JDBC column value object (e.g. <code>String</code> in our case) to the actual mapping object type (e.g. <code>BitSet</code> in this example).</p>
</div>
<div class="paragraph">
<p>The <code>BasicType</code> must be registered, and this can be done at bootstrapping time:</p>
</div>
<div id="basic-custom-type-register-BasicType-example" class="exampleblock">
<div class="title">Example 9. Register a Custom <code>BasicType</code> implementation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">configuration.registerTypeContributor( (typeContributions, serviceRegistry) -&gt; {
    typeContributions.contributeType( BitSetType.INSTANCE );
} );</code></pre>
</div>
</div>
<div class="paragraph">
<p>or using the <code>MetadataBuilder</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">ServiceRegistry standardRegistry =
    new StandardServiceRegistryBuilder().build();

MetadataSources sources = new MetadataSources( standardRegistry );

MetadataBuilder metadataBuilder = sources.getMetadataBuilder();

metadataBuilder.applyBasicType( BitSetType.INSTANCE );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>With the new <code>BitSetType</code> being registered as <code>bitset</code>, the entity mapping looks like this:</p>
</div>
<div id="basic-custom-type-BitSetType-mapping-example" class="exampleblock">
<div class="title">Example 10. Custom <code>BasicType</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    @Type( type = "bitset" )
    private BitSet bitSet;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public BitSet getBitSet() {
        return bitSet;
    }

    public void setBitSet(BitSet bitSet) {
        this.bitSet = bitSet;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To validate this new <code>BasicType</code> implementation, we can test it as follows:</p>
</div>
<div id="basic-custom-type-BitSetType-persistence-example" class="exampleblock">
<div class="title">Example 11. Persisting the custom <code>BasicType</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">BitSet bitSet = BitSet.valueOf( new long[] {1, 2, 3} );

doInHibernate( this::sessionFactory, session -&gt; {
    Product product = new Product( );
    product.setId( 1 );
    product.setBitSet( bitSet );
    session.persist( product );
} );

doInHibernate( this::sessionFactory, session -&gt; {
    Product product = session.get( Product.class, 1 );
    assertEquals(bitSet, product.getBitSet());
} );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When executing this unit test, Hibernate generates the following SQL statements:</p>
</div>
<div id="basic-custom-type-BitSetType-persistence-sql-example" class="exampleblock">
<div class="title">Example 12. Persisting the custom <code>BasicType</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">DEBUG SQL:92 -
    insert
    into
        Product
        (bitSet, id)
    values
        (?, ?)

TRACE BasicBinder:65 - binding parameter [1] as [VARCHAR] - [{0, 65, 128, 129}]
TRACE BasicBinder:65 - binding parameter [2] as [INTEGER] - [1]

DEBUG SQL:92 -
    select
        bitsettype0_.id as id1_0_0_,
        bitsettype0_.bitSet as bitSet2_0_0_
    from
        Product bitsettype0_
    where
        bitsettype0_.id=?

TRACE BasicBinder:65 - binding parameter [1] as [INTEGER] - [1]
TRACE BasicExtractor:61 - extracted value ([bitSet2_0_0_] : [VARCHAR]) - [{0, 65, 128, 129}]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see, the <code>BitSetType</code> takes care of the <em>Java-to-SQL</em> and <em>SQL-to-Java</em> type conversion.</p>
</div>
</div>
<div class="sect4">
<h5 id="basic-custom-type-UserType">Implementing a <code>UserType</code></h5>
<div class="paragraph">
<p>The second approach is to implement the <code>UserType</code> interface.</p>
</div>
<div id="basic-custom-type-BitSetUserType-example" class="exampleblock">
<div class="title">Example 13. Custom <code>UserType</code> implementation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public class BitSetUserType implements UserType {

	public static final BitSetUserType INSTANCE = new BitSetUserType();

    private static final Logger log = Logger.getLogger( BitSetUserType.class );

    @Override
    public int[] sqlTypes() {
        return new int[] {StringType.INSTANCE.sqlType()};
    }

    @Override
    public Class returnedClass() {
        return String.class;
    }

    @Override
    public boolean equals(Object x, Object y)
			throws HibernateException {
        return Objects.equals( x, y );
    }

    @Override
    public int hashCode(Object x)
			throws HibernateException {
        return Objects.hashCode( x );
    }

    @Override
    public Object nullSafeGet(
            ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
            throws HibernateException, SQLException {
        String columnName = names[0];
        String columnValue = (String) rs.getObject( columnName );
        log.debugv("Result set column {0} value is {1}", columnName, columnValue);
        return columnValue == null ? null :
				BitSetTypeDescriptor.INSTANCE.fromString( columnValue );
    }

    @Override
    public void nullSafeSet(
            PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
            throws HibernateException, SQLException {
        if ( value == null ) {
            log.debugv("Binding null to parameter {0} ",index);
            st.setNull( index, Types.VARCHAR );
        }
        else {
            String stringValue = BitSetTypeDescriptor.INSTANCE.toString( (BitSet) value );
            log.debugv("Binding {0} to parameter {1} ", stringValue, index);
            st.setString( index, stringValue );
        }
    }

    @Override
    public Object deepCopy(Object value)
			throws HibernateException {
        return value == null ? null :
            BitSet.valueOf( BitSet.class.cast( value ).toLongArray() );
    }

    @Override
    public boolean isMutable() {
        return true;
    }

    @Override
    public Serializable disassemble(Object value)
			throws HibernateException {
        return (BitSet) deepCopy( value );
    }

    @Override
    public Object assemble(Serializable cached, Object owner)
			throws HibernateException {
        return deepCopy( cached );
    }

    @Override
    public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
        return deepCopy( original );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The entity mapping looks as follows:</p>
</div>
<div id="basic-custom-type-BitSetUserType-mapping-example" class="exampleblock">
<div class="title">Example 14. Custom <code>UserType</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    @Type( type = "bitset" )
    private BitSet bitSet;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public BitSet getBitSet() {
        return bitSet;
    }

    public void setBitSet(BitSet bitSet) {
        this.bitSet = bitSet;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In this example, the <code>UserType</code> is registered under the <code>bitset</code> name, and this is done like this:</p>
</div>
<div id="basic-custom-type-register-UserType-example" class="exampleblock">
<div class="title">Example 15. Register a Custom <code>UserType</code> implementation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">configuration.registerTypeContributor( (typeContributions, serviceRegistry) -&gt; {
    typeContributions.contributeType( BitSetUserType.INSTANCE, "bitset");
} );</code></pre>
</div>
</div>
<div class="paragraph">
<p>or using the <code>MetadataBuilder</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">ServiceRegistry standardRegistry =
    new StandardServiceRegistryBuilder().build();

MetadataSources sources = new MetadataSources( standardRegistry );

MetadataBuilder metadataBuilder = sources.getMetadataBuilder();

metadataBuilder.applyBasicType( BitSetUserType.INSTANCE, "bitset" );</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Like <code>BasicType</code>, you can also register the <code>UserType</code> using a simple name.</p>
</div>
<div class="paragraph">
<p>Without registration, the <code>UserType</code> mapping requires the fully-classified name:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Type( type = "org.hibernate.userguide.mapping.basic.BitSetUserType" )</code></pre>
</div>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>When running the previous test case against the <code>BitSetUserType</code> entity mapping, Hibernate executed the following SQL statements:</p>
</div>
<div id="basic-custom-type-BitSetUserType-persistence-sql-example" class="exampleblock">
<div class="title">Example 16. Persisting the custom <code>BasicType</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">DEBUG SQL:92 -
    insert
    into
        Product
        (bitSet, id)
    values
        (?, ?)

DEBUG BitSetUserType:71 - Binding 1,10,11 to parameter 1
TRACE BasicBinder:65 - binding parameter [2] as [INTEGER] - [1]

DEBUG SQL:92 -
    select
        bitsetuser0_.id as id1_0_0_,
        bitsetuser0_.bitSet as bitSet2_0_0_
    from
        Product bitsetuser0_
    where
        bitsetuser0_.id=?

TRACE BasicBinder:65 - binding parameter [1] as [INTEGER] - [1]
DEBUG BitSetUserType:56 - Result set column bitSet2_0_0_ value is 1,10,11</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="basic-enums">Mapping enums</h4>
<div class="paragraph">
<p>Hibernate supports the mapping of Java enums as basic value types in a number of different ways.</p>
</div>
<div class="sect4">
<h5 id="basic-enums-Enumerated"><code>@Enumerated</code></h5>
<div class="paragraph">
<p>The original JPA-compliant way to map enums was via the <code>@Enumerated</code> and <code>@MapKeyEnumerated</code> for map keys annotations which works on the principle that the enum values are stored according to one of 2 strategies indicated by <code>javax.persistence.EnumType</code>:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>ORDINAL</code></dt>
<dd>
<p>stored according to the enum value&#8217;s ordinal position within the enum class, as indicated by <code>java.lang.Enum#ordinal</code></p>
</dd>
<dt class="hdlist1"><code>STRING</code></dt>
<dd>
<p>stored according to the enum value&#8217;s name, as indicated by <code>java.lang.Enum#name</code></p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>Assuming the following enumeration:</p>
</div>
<div class="exampleblock">
<div class="title">Example 17. <code>PhoneType</code> enumeration</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public enum PhoneType {
    LAND_LINE,
    MOBILE;
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In the ORDINAL example, the <code>phone_type</code> column is defined as an (nullable) INTEGER type and would hold:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>NULL</code></dt>
<dd>
<p>For null values</p>
</dd>
<dt class="hdlist1"><code>0</code></dt>
<dd>
<p>For the <code>LAND_LINE</code> enum</p>
</dd>
<dt class="hdlist1"><code>1</code></dt>
<dd>
<p>For the <code>MOBILE</code> enum</p>
</dd>
</dl>
</div>
<div id="basic-enums-Enumerated-ordinal-example" class="exampleblock">
<div class="title">Example 18. <code>@Enumerated(ORDINAL)</code> example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Phone")
public static class Phone {

    @Id
    private Long id;

    @Column(name = "phone_number")
    private String number;

    @Enumerated(EnumType.ORDINAL)
    @Column(name = "phone_type")
    private PhoneType type;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When persisting this entity, Hibernate generates the following SQL statement:</p>
</div>
<div id="basic-enums-Enumerated-ordinal-persistence-example" class="exampleblock">
<div class="title">Example 19. Persisting an entity with an <code>@Enumerated(ORDINAL)</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Phone phone = new Phone( );
phone.setId( 1L );
phone.setNumber( "123-456-78990" );
phone.setType( PhoneType.MOBILE );
entityManager.persist( phone );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Phone (phone_number, phone_type, id)
VALUES ('123-456-78990', 2, 1)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In the STRING example, the <code>phone_type</code> column is defined as a (nullable) VARCHAR type and would hold:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>NULL</code></dt>
<dd>
<p>For null values</p>
</dd>
<dt class="hdlist1"><code>LAND_LINE</code></dt>
<dd>
<p>For the <code>LAND_LINE</code> enum</p>
</dd>
<dt class="hdlist1"><code>MOBILE</code></dt>
<dd>
<p>For the <code>MOBILE</code> enum</p>
</dd>
</dl>
</div>
<div id="basic-enums-Enumerated-string-example" class="exampleblock">
<div class="title">Example 20. <code>@Enumerated(STRING)</code> example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Phone")
public static class Phone {

    @Id
    private Long id;

    @Column(name = "phone_number")
    private String number;

    @Enumerated(EnumType.STRING)
    @Column(name = "phone_type")
    private PhoneType type;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Persisting the same entity like in the <code>@Enumerated(ORDINAL)</code> example, Hibernate generates the following SQL statement:</p>
</div>
<div id="basic-enums-Enumerated-string-persistence-example" class="exampleblock">
<div class="title">Example 21. Persisting an entity with an <code>@Enumerated(STRING)</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Phone (phone_number, phone_type, id)
VALUES ('123-456-78990', 'MOBILE', 1)</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="basic-enums-attribute-converter">AttributeConverter</h5>
<div class="paragraph">
<p>Let&#8217;s consider the following <code>Gender</code> enum which stores its values using the <code>'M'</code> and <code>'F'</code> codes.</p>
</div>
<div id="basic-enums-converter-example" class="exampleblock">
<div class="title">Example 22. Enum with custom constructor</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public enum Gender {

    MALE( 'M' ),
    FEMALE( 'F' );

    private final char code;

    Gender(char code) {
        this.code = code;
    }

    public static Gender fromCode(char code) {
        if ( code == 'M' || code == 'm' ) {
            return MALE;
        }
        if ( code == 'F' || code == 'f' ) {
            return FEMALE;
        }
        throw new UnsupportedOperationException(
            "The code " + code + " is not supported!"
        );
    }

    public char getCode() {
        return code;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>You can map enums in a JPA compliant way using a JPA 2.1 AttributeConverter.</p>
</div>
<div id="basic-enums-attribute-converter-example" class="exampleblock">
<div class="title">Example 23. Enum mapping with <code>AttributeConverter</code> example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    private String name;

    @Convert( converter = GenderConverter.class )
    public Gender gender;

    //Getters and setters are omitted for brevity

}

@Converter
public static class GenderConverter
        implements AttributeConverter&lt;Gender, Character&gt; {

    public Character convertToDatabaseColumn( Gender value ) {
        if ( value == null ) {
            return null;
        }

        return value.getCode();
    }

    public Gender convertToEntityAttribute( Character value ) {
        if ( value == null ) {
            return null;
        }

        return Gender.fromCode( value );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Here, the gender column is defined as a CHAR type and would hold:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>NULL</code></dt>
<dd>
<p>For null values</p>
</dd>
<dt class="hdlist1"><code>'M'</code></dt>
<dd>
<p>For the <code>MALE</code> enum</p>
</dd>
<dt class="hdlist1"><code>'F'</code></dt>
<dd>
<p>For the <code>FEMALE</code> enum</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>For additional details on using AttributeConverters, see <a href="#basic-jpa-convert">JPA 2.1 AttributeConverters</a> section.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>JPA explicitly disallows the use of an AttributeConverter with an attribute marked as <code>@Enumerated</code>.
So if using the AttributeConverter approach, be sure not to mark the attribute as <code>@Enumerated</code>.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect4">
<h5 id="basic-enums-custom-type">Custom type</h5>
<div class="paragraph">
<p>You can also map enums using a Hibernate custom type mapping.
Let&#8217;s again revisit the Gender enum example, this time using a custom Type to store the more standardized <code>'M'</code> and <code>'F'</code> codes.</p>
</div>
<div id="basic-enums-custom-type-example" class="exampleblock">
<div class="title">Example 24. Enum mapping with custom Type example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    private String name;

    @Type( type = "org.hibernate.userguide.mapping.basic.GenderType" )
    public Gender gender;

    //Getters and setters are omitted for brevity

}

public class GenderType extends AbstractSingleColumnStandardBasicType&lt;Gender&gt; {

    public static final GenderType INSTANCE = new GenderType();

    public GenderType() {
        super(
            CharTypeDescriptor.INSTANCE,
            GenderJavaTypeDescriptor.INSTANCE
        );
    }

    public String getName() {
        return "gender";
    }

    @Override
    protected boolean registerUnderJavaType() {
        return true;
    }
}

public class GenderJavaTypeDescriptor extends AbstractTypeDescriptor&lt;Gender&gt; {

    public static final GenderJavaTypeDescriptor INSTANCE =
        new GenderJavaTypeDescriptor();

    protected GenderJavaTypeDescriptor() {
        super( Gender.class );
    }

    public String toString(Gender value) {
        return value == null ? null : value.name();
    }

    public Gender fromString(String string) {
        return string == null ? null : Gender.valueOf( string );
    }

    public &lt;X&gt; X unwrap(Gender value, Class&lt;X&gt; type, WrapperOptions options) {
        return CharacterTypeDescriptor.INSTANCE.unwrap(
            value == null ? null : value.getCode(),
            type,
            options
        );
    }

    public &lt;X&gt; Gender wrap(X value, WrapperOptions options) {
        return Gender.fromCode(
            CharacterTypeDescriptor.INSTANCE.wrap( value, options )
        );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Again, the gender column is defined as a CHAR type and would hold:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>NULL</code></dt>
<dd>
<p>For null values</p>
</dd>
<dt class="hdlist1"><code>'M'</code></dt>
<dd>
<p>For the <code>MALE</code> enum</p>
</dd>
<dt class="hdlist1"><code>'F'</code></dt>
<dd>
<p>For the <code>FEMALE</code> enum</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>For additional details on using custom types, see <a href="#basic-custom-type">Custom BasicTypes</a> section.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="basic-lob">Mapping LOBs</h4>
<div class="paragraph">
<p>Mapping LOBs (database Large Objects) come in 2 forms, those using the JDBC locator types and those materializing the LOB data.</p>
</div>
<div class="paragraph">
<p>JDBC LOB locators exist to allow efficient access to the LOB data.
They allow the JDBC driver to stream parts of the LOB data as needed, potentially freeing up memory space.
However they can be unnatural to deal with and have certain limitations.
For example, a LOB locator is only portably valid during the duration of the transaction in which it was obtained.</p>
</div>
<div class="paragraph">
<p>The idea of materialized LOBs is to trade-off the potential efficiency (not all drivers handle LOB data efficiently) for a more natural programming paradigm using familiar Java types such as String or byte[], etc for these LOBs.</p>
</div>
<div class="paragraph">
<p>Materialized deals with the entire LOB contents in memory, whereas LOB locators (in theory) allow streaming parts of the LOB contents into memory as needed.</p>
</div>
<div class="paragraph">
<p>The JDBC LOB locator types include:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>java.sql.Blob</code></p>
</li>
<li>
<p><code>java.sql.Clob</code></p>
</li>
<li>
<p><code>java.sql.NClob</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Mapping materialized forms of these LOB values would use more familiar Java types such as <code>String</code>, <code>char[]</code>, <code>byte[]</code>, etc.
The trade off for <em>more familiar</em> is usually performance.</p>
</div>
<div class="paragraph">
<p>For a first look, let&#8217;s assume we have a <code>CLOB</code> column that we would like to map (<code>NCLOB</code> character <code>LOB</code> data will be covered in <a href="#basic-nationalized">Mapping Nationalized Character Data</a> section).</p>
</div>
<div id="basic-clob-sql-example" class="exampleblock">
<div class="title">Example 25. CLOB - SQL</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Product (
  id INTEGER NOT NULL
  image clob
  name VARCHAR(255)
  PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s first map this using the <code>@Lob</code> JPA annotation and the <code>java.sql.Clob</code> type:</p>
</div>
<div id="basic-clob-example" class="exampleblock">
<div class="title">Example 26. <code>CLOB</code> mapped to <code>java.sql.Clob</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Lob
    private Clob warranty;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To persist such an entity, you have to create a <code>Clob</code> using plain JDBC:</p>
</div>
<div id="basic-clob-persist-example" class="exampleblock">
<div class="title">Example 27. Persisting a <code>java.sql.Clob</code> entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">String warranty = "My product warranty";

final Product product = new Product();
product.setId( 1 );
product.setName( "Mobile phone" );

session.doWork( connection -&gt; {
    product.setWarranty( ClobProxy.generateProxy( warranty ) );
} );

entityManager.persist( product );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To retrieve the <code>Clob</code> content, you need to transform the underlying <code>java.io.Reader</code>:</p>
</div>
<div id="basic-clob-find-example" class="exampleblock">
<div class="title">Example 28. Returning a <code>java.sql.Clob</code> entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Product product = entityManager.find( Product.class, productId );
try (Reader reader = product.getWarranty().getCharacterStream()) {
    assertEquals( "My product warranty", toString( reader ) );
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>We could also map the CLOB in a materialized form. This way, we can either use a <code>String</code> or a <code>char[]</code>.</p>
</div>
<div id="basic-clob-string-example" class="exampleblock">
<div class="title">Example 29. <code>CLOB</code> mapped to <code>String</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Lob
    private String warranty;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>How JDBC deals with <code>LOB</code> data varies from driver to driver, and Hibernate tries to handle all these variances on your behalf.</p>
</div>
<div class="paragraph">
<p>However, some drivers are trickier (e.g. PostgreSQL JDBC drivers), and, in such cases, you may have to do some extra to get LOBs working.
Such discussions are beyond the scope of this guide.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>We might even want the materialized data as a char array (for some crazy reason).</p>
</div>
<div id="basic-clob-char-array-example" class="exampleblock">
<div class="title">Example 30. CLOB - materialized <code>char[]</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Lob
    private char[] warranty;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p><code>BLOB</code> data is mapped in a similar fashion.</p>
</div>
<div id="basic-blob-sql-example" class="exampleblock">
<div class="title">Example 31. BLOB - SQL</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Product (
    id INTEGER NOT NULL ,
    image blob ,
    name VARCHAR(255) ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s first map this using the JDBC <code>java.sql.Blob</code> type.</p>
</div>
<div id="basic-blob-example" class="exampleblock">
<div class="title">Example 32. <code>BLOB</code> mapped to <code>java.sql.Blob</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Lob
    private Blob image;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To persist such an entity, you have to create a <code>Blob</code> using plain JDBC:</p>
</div>
<div id="basic-blob-persist-example" class="exampleblock">
<div class="title">Example 33. Persisting a <code>java.sql.Blob</code> entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">byte[] image = new byte[] {1, 2, 3};

final Product product = new Product();
product.setId( 1 );
product.setName( "Mobile phone" );

session.doWork( connection -&gt; {
    product.setImage( BlobProxy.generateProxy( image ) );
} );

entityManager.persist( product );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To retrieve the <code>Blob</code> content, you need to transform the underlying <code>java.io.Reader</code>:</p>
</div>
<div id="basic-blob-find-example" class="exampleblock">
<div class="title">Example 34. Returning a <code>java.sql.Blob</code> entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Product product = entityManager.find( Product.class, productId );

try (InputStream inputStream = product.getImage().getBinaryStream()) {
    assertArrayEquals(new byte[] {1, 2, 3}, toBytes( inputStream ) );
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>We could also map the BLOB in a materialized form (e.g. <code>byte[]</code>).</p>
</div>
<div id="basic-blob-byte-array-example" class="exampleblock">
<div class="title">Example 35. <code>BLOB</code> mapped to <code>byte[]</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Lob
    private byte[] image;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="basic-nationalized">Mapping Nationalized Character Data</h4>
<div class="paragraph">
<p>JDBC 4 added the ability to explicitly handle nationalized character data.
To this end it added specific nationalized character data types.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>NCHAR</code></p>
</li>
<li>
<p><code>NVARCHAR</code></p>
</li>
<li>
<p><code>LONGNVARCHAR</code></p>
</li>
<li>
<p><code>NCLOB</code></p>
</li>
</ul>
</div>
<div id="basic-nationalized-sql-example" class="exampleblock">
<div class="title">Example 36. <code>NVARCHAR</code> - SQL</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">CREATE TABLE Product (
    id INTEGER NOT NULL ,
    name VARCHAR(255) ,
    warranty NVARCHAR(255) ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To map a specific attribute to a nationalized variant data type, Hibernate defines the <code>@Nationalized</code> annotation.</p>
</div>
<div id="basic-nationalized-example" class="exampleblock">
<div class="title">Example 37. <code>NVARCHAR</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Nationalized
    private String warranty;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Just like with <code>CLOB</code>, Hibernate can also deal with <code>NCLOB</code> SQL data types:</p>
</div>
<div id="basic-nclob-sql-example" class="exampleblock">
<div class="title">Example 38. <code>NCLOB</code> - SQL</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">CREATE TABLE Product (
    id INTEGER NOT NULL ,
    name VARCHAR(255) ,
    warranty nclob ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Hibernate can map the <code>NCLOB</code> to a <code>java.sql.NClob</code></p>
</div>
<div id="basic-nclob-example" class="exampleblock">
<div class="title">Example 39. <code>NCLOB</code> mapped to <code>java.sql.NClob</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Lob
    @Nationalized
    // Clob also works, because NClob extends Clob.
    // The database type is still NCLOB either way and handled as such.
    private NClob warranty;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To persist such an entity, you have to create a <code>NClob</code> using plain JDBC:</p>
</div>
<div id="basic-nclob-persist-example" class="exampleblock">
<div class="title">Example 40. Persisting a <code>java.sql.NClob</code> entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">String warranty = "My product warranty";

final Product product = new Product();
product.setId( 1 );
product.setName( "Mobile phone" );

session.doWork( connection -&gt; {
    product.setWarranty( connection.createNClob() );
    product.getWarranty().setString( 1, warranty );
} );

entityManager.persist( product );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To retrieve the <code>NClob</code> content, you need to transform the underlying <code>java.io.Reader</code>:</p>
</div>
<div id="basic-nclob-find-example" class="exampleblock">
<div class="title">Example 41. Returning a <code>java.sql.NClob</code> entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Product product = entityManager.find( Product.class, productId );
try (Reader reader = product.getWarranty().getCharacterStream()) {
    assertEquals( "My product warranty", toString( reader ) );
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>We could also map the <code>NCLOB</code> in a materialized form. This way, we can either use a <code>String</code> or a <code>char[]</code>.</p>
</div>
<div id="basic-nclob-string-example" class="exampleblock">
<div class="title">Example 42. <code>NCLOB</code> mapped to <code>String</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Lob
    @Nationalized
    private String warranty;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>We might even want the materialized data as a char array.</p>
</div>
<div id="basic-nclob-char-array-example" class="exampleblock">
<div class="title">Example 43. NCLOB - materialized <code>char[]</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Integer id;

    private String name;

    @Lob
    @Nationalized
    private char[] warranty;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>If you application and database are entirely nationalized you may instead want to enable nationalized character data as the default.
You can do this via the <code>hibernate.use_nationalized_character_data</code> setting or by calling <code>MetadataBuilder#enableGlobalNationalizedCharacterDataSupport</code> during bootstrap.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="basic-uuid">Mapping UUID Values</h4>
<div class="paragraph">
<p>Hibernate also allows you to map UUID values, again in a number of ways.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The default UUID mapping is as binary because it represents more efficient storage.
However many applications prefer the readability of character storage.
To switch the default mapping, simply call <code>MetadataBuilder.applyBasicType( UUIDCharType.INSTANCE, UUID.class.getName() )</code>.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_uuid_as_binary">UUID as binary</h4>
<div class="paragraph">
<p>As mentioned, the default mapping for UUID attributes.
Maps the UUID to a <code>byte[]</code> using <code>java.util.UUID#getMostSignificantBits</code> and <code>java.util.UUID#getLeastSignificantBits</code> and stores that as <code>BINARY</code> data.</p>
</div>
<div class="paragraph">
<p>Chosen as the default simply because it is generally more efficient from storage perspective.</p>
</div>
</div>
<div class="sect3">
<h4 id="_uuid_as_var_char">UUID as (var)char</h4>
<div class="paragraph">
<p>Maps the UUID to a String using <code>java.util.UUID#toString</code> and <code>java.util.UUID#fromString</code> and stores that as <code>CHAR</code> or <code>VARCHAR</code> data.</p>
</div>
</div>
<div class="sect3">
<h4 id="_postgesql_specific_uuid">PostgeSQL-specific UUID</h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>When using one of the PostgreSQL Dialects, this becomes the default UUID mapping.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Maps the UUID using PostgreSQL&#8217;s specific UUID data type.
The PostgreSQL JDBC driver chooses to map its UUID type to the <code>OTHER</code> code.
Note that this can cause difficulty as the driver chooses to map many different data types to <code>OTHER</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_uuid_as_identifier">UUID as identifier</h4>
<div class="paragraph">
<p>Hibernate supports using UUID values as identifiers, and they can even be generated on user&#8217;s behalf.
For details, see the discussion of generators in <a href="chapters/domain/identifiers.html#identifiers"><em>Identifier generators</em></a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="basic-datetime">Mapping Date/Time Values</h4>
<div class="paragraph">
<p>Hibernate allows various Java Date/Time classes to be mapped as persistent domain model entity properties.
The SQL standard defines three Date/Time types:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">DATE</dt>
<dd>
<p>Represents a calendar date by storing years, months and days. The JDBC equivalent is <code>java.sql.Date</code></p>
</dd>
<dt class="hdlist1">TIME</dt>
<dd>
<p>Represents the time of a day and it stores hours, minutes and seconds. The JDBC equivalent is <code>java.sql.Time</code></p>
</dd>
<dt class="hdlist1">TIMESTAMP</dt>
<dd>
<p>It stores both a DATE and a TIME plus nanoseconds. The JDBC equivalent is <code>java.sql.Timestamp</code></p>
</dd>
</dl>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>To avoid dependencies on the <code>java.sql</code> package, it&#8217;s common to use the <code>java.util</code> or <code>java.time</code> Date/Time classes instead.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>While the <code>java.sql</code> classes define a direct association to the SQL Date/Time data types,
the <code>java.util</code> or <code>java.time</code> properties need to explicitly mark the SQL type correlation with the <code>@Temporal</code> annotation.
This way, a <code>java.util.Date</code> or a <code>java.util.Calendar</code> can be mapped to either an SQL <code>DATE</code>, <code>TIME</code> or <code>TIMESTAMP</code> type.</p>
</div>
<div class="paragraph">
<p>Considering the following entity:</p>
</div>
<div id="basic-datetime-temporal-date-example" class="exampleblock">
<div class="title">Example 44. <code>java.util.Date</code> mapped as <code>DATE</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "DateEvent")
public static class DateEvent {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`timestamp`")
    @Temporal(TemporalType.DATE)
    private Date timestamp;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When persisting such entity:</p>
</div>
<div id="basic-datetime-temporal-date-persist-example" class="exampleblock">
<div class="title">Example 45. Persisting a <code>java.util.Date</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">DateEvent dateEvent = new DateEvent( new Date() );
entityManager.persist( dateEvent );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Hibernate generates the following INSERT statement:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO DateEvent ( timestamp, id )
VALUES ( '2015-12-29', 1 )</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Only the year, month and the day field were saved into the database.</p>
</div>
<div class="paragraph">
<p>If we change the <code>@Temporal</code> type to <code>TIME</code>:</p>
</div>
<div id="basic-datetime-temporal-time-example" class="exampleblock">
<div class="title">Example 46. <code>java.util.Date</code> mapped as <code>TIME</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Column(name = "`timestamp`")
@Temporal(TemporalType.TIME)
private Date timestamp;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Hibernate will issue an INSERT statement containing the hour, minutes and seconds.</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO DateEvent ( timestamp, id )
VALUES ( '16:51:58', 1 )</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When the <code>@Temporal</code> type is set to <code>TIMESTAMP</code>:</p>
</div>
<div id="basic-datetime-temporal-timestamp-example" class="exampleblock">
<div class="title">Example 47. <code>java.util.Date</code> mapped as <code>TIMESTAMP</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Column(name = "`timestamp`")
@Temporal(TemporalType.TIMESTAMP)
private Date timestamp;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Hibernate will include both the <code>DATE</code>, the <code>TIME</code> and the nanoseconds in the INSERT statement:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO DateEvent ( timestamp, id )
VALUES ( '2015-12-29 16:54:04.544', 1 )</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Just like the <code>java.util.Date</code>, the <code>java.util.Calendar</code> requires the <code>@Temporal</code> annotation in order to know what JDBC data type to be chosen: DATE, TIME or TIMESTAMP.
If the <code>java.util.Date</code> marks a point in time, the <code>java.util.Calendar</code> takes into consideration the default Time Zone.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect4">
<h5 id="basic-datetime-java8">Mapping Java 8 Date/Time Values</h5>
<div class="paragraph">
<p>Java 8 came with a new Date/Time API, offering support for instant dates, intervals, local and zoned Date/Time immutable instances, bundled in the <code>java.time</code> package.</p>
</div>
<div class="paragraph">
<p>The mapping between the standard SQL Date/Time types and the supported Java 8 Date/Time class types looks as follows;</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">DATE</dt>
<dd>
<p><code>java.time.LocalDate</code></p>
</dd>
<dt class="hdlist1">TIME</dt>
<dd>
<p><code>java.time.LocalTime</code>, <code>java.time.OffsetTime</code></p>
</dd>
<dt class="hdlist1">TIMESTAMP</dt>
<dd>
<p><code>java.time.Instant</code>, <code>java.time.LocalDateTime</code>, <code>java.time.OffsetDateTime</code> and <code>java.time.ZonedDateTime</code></p>
</dd>
</dl>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Because the mapping between Java 8 Date/Time classes and the SQL types is implicit, there is not need to specify the <code>@Temporal</code> annotation.
Setting it on the <code>java.time</code> classes throws the following exception:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property</pre>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect4">
<h5 id="basic-datetime-time-zone">Using a specific time zone</h5>
<div class="paragraph">
<p>By default, Hibernate is going to use the <a href="https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#setTimestamp-int-java.sql.Timestamp-"><code>PreparedStatement.setTimestamp(int parameterIndex, java.sql.Timestamp)</code></a> or
<a href="https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#setTime-int-java.sql.Time-"><code>PreparedStatement.setTime(int parameterIndex, java.sql.Time x)</code></a> when saving a <code>java.sql.Timestamp</code> or a <code>java.sql.Time</code> property.</p>
</div>
<div class="paragraph">
<p>When the time zone is not specified, the JDBC driver is going to use the underlying JVM default time zone, which might not be suitable if the application is used from all across the globe.
For this reason, it is very common to use a single reference time zone (e.g. UTC) whenever saving/loading data from the database.</p>
</div>
<div class="paragraph">
<p>One alternative would be to configure all JVMs to use the reference time zone:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Declaratively</dt>
<dd>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">java -Duser.timezone=UTC ...</code></pre>
</div>
</div>
</dd>
<dt class="hdlist1">Programmatically</dt>
<dd>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">TimeZone.setDefault( TimeZone.getTimeZone( "UTC" ) );</code></pre>
</div>
</div>
</dd>
</dl>
</div>
<div class="paragraph">
<p>However, as explained in <a href="http://in.relation.to/2016/09/12/jdbc-time-zone-configuration-property/">this article</a>, this is not always practical especially for front-end nodes.
For this reason, Hibernate offers the <code>hibernate.jdbc.time_zone</code> configuration property which can be configured:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Declaratively, at the <code>SessionFactory</code> level</dt>
<dd>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">settings.put(
    AvailableSettings.JDBC_TIME_ZONE,
    TimeZone.getTimeZone( "UTC" )
);</code></pre>
</div>
</div>
</dd>
<dt class="hdlist1">Programmatically, on a per <code>Session</code> basis</dt>
<dd>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session = sessionFactory()
    .withOptions()
    .jdbcTimeZone( TimeZone.getTimeZone( "UTC" ) )
    .openSession();</code></pre>
</div>
</div>
</dd>
</dl>
</div>
<div class="paragraph">
<p>With this configuration property in place, Hibernate is going to call the <a href="https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#setTimestamp-int-java.sql.Timestamp-java.util.Calendar-"><code>PreparedStatement.setTimestamp(int parameterIndex, java.sql.Timestamp, Calendar cal)</code></a> or
<a href="https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#setTime-int-java.sql.Time-java.util.Calendar-"><code>PreparedStatement.setTime(int parameterIndex, java.sql.Time x, Calendar cal)</code></a>, where the <code>java.util.Calendar</code> references the time zone provided via the <code>hibernate.jdbc.time_zone</code> property.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="basic-jpa-convert">JPA 2.1 AttributeConverters</h4>
<div class="paragraph">
<p>Although Hibernate has long been offering <a href="#basic-custom-type">custom types</a>, as a JPA 2.1 provider,
it also supports <code>AttributeConverter</code> as well.</p>
</div>
<div class="paragraph">
<p>With a custom <code>AttributeConverter</code>, the application developer can map a given JDBC type to an entity basic type.</p>
</div>
<div class="paragraph">
<p>In the following example, the <code>java.util.Period</code> is going to be mapped to a <code>VARCHAR</code> database column.</p>
</div>
<div id="basic-jpa-convert-period-string-converter-example" class="exampleblock">
<div class="title">Example 48. <code>java.util.Period</code> custom <code>AttributeConverter</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Converter
public class PeriodStringConverter
        implements AttributeConverter&lt;Period, String&gt; {

    @Override
    public String convertToDatabaseColumn(Period attribute) {
        return attribute.toString();
    }

    @Override
    public Period convertToEntityAttribute(String dbData) {
        return Period.parse( dbData );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To make use of this custom converter, the <code>@Convert</code> annotation must decorate the entity attribute.</p>
</div>
<div id="basic-jpa-convert-period-string-converter-mapping-example" class="exampleblock">
<div class="title">Example 49. Entity using the custom <code>java.util.Period</code> <code>AttributeConverter</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Event")
public static class Event {

    @Id
    @GeneratedValue
    private Long id;

    @Convert(converter = PeriodStringConverter.class)
    @Column(columnDefinition = "")
    private Period span;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When persisting such entity, Hibernate will do the type conversion based on the <code>AttributeConverter</code> logic:</p>
</div>
<div id="basic-jpa-convert-period-string-converter-sql-example" class="exampleblock">
<div class="title">Example 50. Persisting entity using the custom <code>AttributeConverter</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Event ( span, id )
VALUES ( 'P1Y2M3D', 1 )</code></pre>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="basic-jpa-convert-type"><code>AttributeConverter</code> Java and JDBC types</h5>
<div class="paragraph">
<p>In cases when the Java type specified for the "database side" of the conversion (the second <code>AttributeConverter</code> bind parameter) is not known,
Hibernate will fallback to a <code>java.io.Serializable</code> type.</p>
</div>
<div class="paragraph">
<p>If the Java type is not know to Hibernate, you will encounter the following message:</p>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>HHH000481: Encountered Java type for which we could not locate a JavaTypeDescriptor and which does not appear to implement equals and/or hashCode.
This can lead to significant performance problems when performing equality/dirty checking involving this Java type.
Consider registering a custom JavaTypeDescriptor or at least implementing equals/hashCode.</p>
</div>
</blockquote>
</div>
<div class="paragraph">
<p>Whether a Java type is "known" means it has an entry in the <code>JavaTypeDescriptorRegistry</code>.
While by default Hibernate loads many JDK types into the <code>JavaTypeDescriptorRegistry</code>, an application can also expand the <code>JavaTypeDescriptorRegistry</code> by
adding new <code>JavaTypeDescriptor</code> entries.</p>
</div>
<div class="paragraph">
<p>This way, Hibernate will also know how to handle a specific Java Object type at the JDBC level.</p>
</div>
</div>
<div class="sect4">
<h5 id="basic-jpa-convert-mutability">JPA 2.1 <code>AttributeConverter</code> Mutability Plan</h5>
<div class="paragraph">
<p>A basic type that&#8217;s converted by a JPA <code>AttributeConverter</code> is immutable if the underlying Java type is immutable
and is mutable if the associated attribute type is mutable as well.</p>
</div>
<div class="paragraph">
<p>Therefore, mutability is given by the <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/type/descriptor/java/JavaTypeDescriptor.html#getMutabilityPlan--"><code>JavaTypeDescriptor#getMutabilityPlan</code></a>
of the associated entity attribute type.</p>
</div>
<div class="sect5">
<h6 id="_immutable_types">Immutable types</h6>
<div class="paragraph">
<p>If the entity attribute is a <code>String</code>, a primitive wrapper (e.g. <code>Integer</code>, <code>Long</code>) an Enum type, or any other immutable <code>Object</code> type,
then you can only change the entity attribute value by reassigning it to a new value.</p>
</div>
<div class="paragraph">
<p>Considering we have the same <code>Period</code> entity attribute as illustrated in the <a href="#basic-jpa-convert">JPA 2.1 AttributeConverters</a> section:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Event")
public static class Event {

    @Id
    @GeneratedValue
    private Long id;

    @Convert(converter = PeriodStringConverter.class)
    @Column(columnDefinition = "")
    private Period span;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The only way to change the <code>span</code> attribute is to reassign it to a different value:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Event event = entityManager.createQuery( "from Event", Event.class ).getSingleResult();
event.setSpan(Period
    .ofYears( 3 )
    .plusMonths( 2 )
    .plusDays( 1 )
);</code></pre>
</div>
</div>
</div>
<div class="sect5">
<h6 id="_mutable_types">Mutable types</h6>
<div class="paragraph">
<p>On the other hand, consider the following example where the <code>Money</code> type is a mutable.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public static class Money {

    private long cents;

    public Money(long cents) {
        this.cents = cents;
    }

    public long getCents() {
        return cents;
    }

    public void setCents(long cents) {
        this.cents = cents;
    }
}

public static class MoneyConverter
        implements AttributeConverter&lt;Money, Long&gt; {

    @Override
    public Long convertToDatabaseColumn(Money attribute) {
        return attribute == null ? null : attribute.getCents();
    }

    @Override
    public Money convertToEntityAttribute(Long dbData) {
        return dbData == null ? null : new Money( dbData );
    }
}

@Entity(name = "Account")
public static class Account {

    @Id
    private Long id;

    private String owner;

    @Convert(converter = MoneyConverter.class)
    private Money balance;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
<div class="paragraph">
<p>A mutable <code>Object</code> allows you to modify its internal structure, and Hibernate dirty checking mechanism is going to propagate the change to the database:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Account account = entityManager.find( Account.class, 1L );
account.getBalance().setCents( 150 * 100L );
entityManager.persist( account );</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Although the <code>AttributeConverter</code> types can be mutable so that dirty checking, deep copying and second-level caching work properly,
treating these as immutable (when they really are) is more efficient.</p>
</div>
<div class="paragraph">
<p>For this reason, prefer immutable types over mutable ones whenever possible.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-quoted-identifiers">SQL quoted identifiers</h4>
<div class="paragraph">
<p>You can force Hibernate to quote an identifier in the generated SQL by enclosing the table or column name in backticks in the mapping document.
While traditionally, Hibernate used backticks for escaping SQL reserved keywords, JPA uses double quotes instead.</p>
</div>
<div class="paragraph">
<p>Once the reserved keywords are escaped, Hibernate will use the correct quotation style for the SQL <code>Dialect</code>.
This is usually double quotes, but SQL Server uses brackets and MySQL uses backticks.</p>
</div>
<div id="basic-quoting-example" class="exampleblock">
<div class="title">Example 51. Hibernate legacy quoting</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Long id;

    @Column(name = "`name`")
    private String name;

    @Column(name = "`number`")
    private String number;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div id="basic-jpa-quoting-example" class="exampleblock">
<div class="title">Example 52. JPA quoting</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Long id;

    @Column(name = "\"name\"")
    private String name;

    @Column(name = "\"number\"")
    private String number;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Because <code>name</code> and <code>number</code> are reserved words, the <code>Product</code> entity mapping uses backtricks to quote these column names.</p>
</div>
<div class="paragraph">
<p>When saving the following <code>Product entity</code>, Hibernate generates the following SQL insert statement:</p>
</div>
<div id="basic-quoting-persistence-example" class="exampleblock">
<div class="title">Example 53. Persisting a quoted column name</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Product product = new Product();
product.setId( 1L );
product.setName( "Mobile phone" );
product.setNumber( "123-456-7890" );
entityManager.persist( product );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Product ("name", "number", id)
VALUES ('Mobile phone', '123-456-7890', 1)</code></pre>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="mapping-global-quoted-identifiers">Global quoting</h5>
<div class="paragraph">
<p>Hibernate can also quote all identifiers (e.g. table, columns) using the following configuration property:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml">&lt;property
    name="hibernate.globally_quoted_identifiers"
    value="true"
/&gt;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This way, we don&#8217;t need to manually quote any identifier:</p>
</div>
<div id="basic-auto-quoting-example" class="exampleblock">
<div class="title">Example 54. JPA quoting</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    private Long id;

    private String name;

    private String number;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When persisting a <code>Product</code> entity, Hibernate is going to quote all identifiers as in the following example:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO "Product" ("name", "number", "id")
VALUES ('Mobile phone', '123-456-7890', 1)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see, both the table name and all the column have been quoted.</p>
</div>
<div class="paragraph">
<p>For more about quoting-related configuration properties, check out the <a href="appendices/Configurations.html#configurations-mapping">Mapping configurations</a> section as well.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-generated">Generated properties</h4>
<div class="paragraph">
<p>Generated properties are properties that have their values generated by the database.
Typically, Hibernate applications needed to <code>refresh</code> objects that contain any properties for which the database was generating values.
Marking properties as generated, however, lets the application delegate this responsibility to Hibernate.
When Hibernate issues an SQL INSERT or UPDATE for an entity that has defined generated properties, it immediately issues a select to retrieve the generated values.</p>
</div>
<div class="paragraph">
<p>Properties marked as generated must additionally be <em>non-insertable</em> and <em>non-updateable</em>.
Only <code>@Version</code> and <code>@Basic</code> types can be marked as generated.</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>NEVER</code> (the default)</dt>
<dd>
<p>the given property value is not generated within the database.</p>
</dd>
<dt class="hdlist1"><code>INSERT</code></dt>
<dd>
<p>the given property value is generated on insert, but is not regenerated on subsequent updates. Properties like <em>creationTimestamp</em> fall into this category.</p>
</dd>
<dt class="hdlist1"><code>ALWAYS</code></dt>
<dd>
<p>the property value is generated both on insert and on update.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>To mark a property as generated, use The Hibernate specific <code>@Generated</code> annotation.</p>
</div>
<div class="sect4">
<h5 id="mapping-generated-Generated"><code>@Generated</code> annotation</h5>
<div class="paragraph">
<p>The <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/Generated.html"><code>@Generated</code></a> annotation is used so that Hibernate can fetch the currently annotated property after the entity has been persisted or updated.
For this reason, the <code>@Generated</code> annotation accepts a <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/GenerationTime.html"><code>GenerationTime</code></a> enum value.</p>
</div>
<div class="paragraph">
<p>Considering the following entity:</p>
</div>
<div id="mapping-generated-Generated-example" class="exampleblock">
<div class="title">Example 55. <code>@Generated</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    private String firstName;

    private String lastName;

    private String middleName1;

    private String middleName2;

    private String middleName3;

    private String middleName4;

    private String middleName5;

    @Generated( value = GenerationTime.ALWAYS )
    @Column(columnDefinition =
        "AS CONCAT(" +
        "    COALESCE(firstName, ''), " +
        "    COALESCE(' ' + middleName1, ''), " +
        "    COALESCE(' ' + middleName2, ''), " +
        "    COALESCE(' ' + middleName3, ''), " +
        "    COALESCE(' ' + middleName4, ''), " +
        "    COALESCE(' ' + middleName5, ''), " +
        "    COALESCE(' ' + lastName, '') " +
        ")")
    private String fullName;

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When the <code>Person</code> entity is persisted, Hibernate is going to fetch the calculated <code>fullName</code> column from the database,
which concatenates the first, middle, and last name.</p>
</div>
<div id="mapping-generated-Generated-persist-example" class="exampleblock">
<div class="title">Example 56. <code>@Generated</code> persist example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Person person = new Person();
person.setId( 1L );
person.setFirstName( "John" );
person.setMiddleName1( "Flávio" );
person.setMiddleName2( "André" );
person.setMiddleName3( "Frederico" );
person.setMiddleName4( "Rúben" );
person.setMiddleName5( "Artur" );
person.setLastName( "Doe" );

entityManager.persist( person );
entityManager.flush();

assertEquals("John Flávio André Frederico Rúben Artur Doe", person.getFullName());</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Person
(
    firstName,
    lastName,
    middleName1,
    middleName2,
    middleName3,
    middleName4,
    middleName5,
    id
)
values
(?, ?, ?, ?, ?, ?, ?, ?)

-- binding parameter [1] as [VARCHAR] - [John]
-- binding parameter [2] as [VARCHAR] - [Doe]
-- binding parameter [3] as [VARCHAR] - [Flávio]
-- binding parameter [4] as [VARCHAR] - [André]
-- binding parameter [5] as [VARCHAR] - [Frederico]
-- binding parameter [6] as [VARCHAR] - [Rúben]
-- binding parameter [7] as [VARCHAR] - [Artur]
-- binding parameter [8] as [BIGINT]  - [1]

SELECT
    p.fullName as fullName3_0_
FROM
    Person p
WHERE
    p.id=?

-- binding parameter [1] as [BIGINT] - [1]
-- extracted value ([fullName3_0_] : [VARCHAR]) - [John Flávio André Frederico Rúben Artur Doe]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The same goes when the <code>Person</code> entity is updated.
Hibernate is going to fetch the calculated <code>fullName</code> column from the database after the entity is modified.</p>
</div>
<div id="mapping-generated-Generated-update-example" class="exampleblock">
<div class="title">Example 57. <code>@Generated</code> update example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Person person = entityManager.find( Person.class, 1L );
person.setLastName( "Doe Jr" );

entityManager.flush();
assertEquals("John Flávio André Frederico Rúben Artur Doe Jr", person.getFullName());</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">UPDATE
    Person
SET
    firstName=?,
    lastName=?,
    middleName1=?,
    middleName2=?,
    middleName3=?,
    middleName4=?,
    middleName5=?
WHERE
    id=?

-- binding parameter [1] as [VARCHAR] - [John]
-- binding parameter [2] as [VARCHAR] - [Doe Jr]
-- binding parameter [3] as [VARCHAR] - [Flávio]
-- binding parameter [4] as [VARCHAR] - [André]
-- binding parameter [5] as [VARCHAR] - [Frederico]
-- binding parameter [6] as [VARCHAR] - [Rúben]
-- binding parameter [7] as [VARCHAR] - [Artur]
-- binding parameter [8] as [BIGINT]  - [1]

SELECT
    p.fullName as fullName3_0_
FROM
    Person p
WHERE
    p.id=?

-- binding parameter [1] as [BIGINT] - [1]
-- extracted value ([fullName3_0_] : [VARCHAR]) - [John Flávio André Frederico Rúben Artur Doe Jr]</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="mapping-generated-GeneratorType"><code>@GeneratorType</code> annotation</h5>
<div class="paragraph">
<p>The <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/GeneratorType.html"><code>@GeneratorType</code></a> annotation is used so that
you can provide a custom generator to set the value of the currently annotated property.</p>
</div>
<div class="paragraph">
<p>For this reason, the <code>@GeneratorType</code> annotation accepts a <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/GenerationTime.html"><code>GenerationTime</code></a> enum value
and a custom <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/ValueGenerator.html"><code>ValueGenerator</code></a> class type.</p>
</div>
<div class="paragraph">
<p>Considering the following entity:</p>
</div>
<div id="mapping-generated-GeneratorType-example" class="exampleblock">
<div class="title">Example 58. <code>@GeneratorType</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public static class CurrentUser {

    public static final CurrentUser INSTANCE = new CurrentUser();

    private static final ThreadLocal&lt;String&gt; storage = new ThreadLocal&lt;&gt;();

    public void logIn(String user) {
        storage.set( user );
    }

    public void logOut() {
        storage.remove();
    }

    public String get() {
        return storage.get();
    }
}

public static class LoggedUserGenerator implements ValueGenerator&lt;String&gt; {

    @Override
    public String generateValue(
            Session session, Object owner) {
        return CurrentUser.INSTANCE.get();
    }
}

@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    private String firstName;

    private String lastName;

    @GeneratorType( type = LoggedUserGenerator.class, when = GenerationTime.INSERT)
    private String createdBy;

    @GeneratorType( type = LoggedUserGenerator.class, when = GenerationTime.ALWAYS)
    private String updatedBy;

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When the <code>Person</code> entity is persisted, Hibernate is going to populate the <code>createdBy</code> column with the currently logged user.</p>
</div>
<div id="mapping-generated-GeneratorType-persist-example" class="exampleblock">
<div class="title">Example 59. <code>@Generated</code> persist example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">CurrentUser.INSTANCE.logIn( "Alice" );

doInJPA( this::entityManagerFactory, entityManager -&gt; {

    Person person = new Person();
    person.setId( 1L );
    person.setFirstName( "John" );
    person.setLastName( "Doe" );

    entityManager.persist( person );
} );

CurrentUser.INSTANCE.logOut();</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Person
(
    createdBy,
    firstName,
    lastName,
    updatedBy,
    id
)
VALUES
(?, ?, ?, ?, ?)

-- binding parameter [1] as [VARCHAR] - [Alice]
-- binding parameter [2] as [VARCHAR] - [John]
-- binding parameter [3] as [VARCHAR] - [Doe]
-- binding parameter [4] as [VARCHAR] - [Alice]
-- binding parameter [5] as [BIGINT]  - [1]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The same goes when the <code>Person</code> entity is updated.
Hibernate is going to populate the <code>updatedBy</code> column with the currently logged user.</p>
</div>
<div id="mapping-generated-GeneratorType-update-example" class="exampleblock">
<div class="title">Example 60. <code>@Generated</code> update example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">CurrentUser.INSTANCE.logIn( "Bob" );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Person person = entityManager.find( Person.class, 1L );
    person.setFirstName( "Mr. John" );
} );

CurrentUser.INSTANCE.logOut();</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">UPDATE Person
SET
    createdBy = ?,
    firstName = ?,
    lastName = ?,
    updatedBy = ?
WHERE
    id = ?

-- binding parameter [1] as [VARCHAR] - [Alice]
-- binding parameter [2] as [VARCHAR] - [Mr. John]
-- binding parameter [3] as [VARCHAR] - [Doe]
-- binding parameter [4] as [VARCHAR] - [Bob]
-- binding parameter [5] as [BIGINT]  - [1]</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="mapping-generated-CreationTimestamp"><code>@CreationTimestamp</code> annotation</h5>
<div class="paragraph">
<p>The <code>@CreationTimestamp</code> annotation instructs Hibernate to set the annotated entity attribute with the current timestamp value of the JVM
when the entity is being persisted.</p>
</div>
<div class="paragraph">
<p>The supported property types are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>java.util.Date</code></p>
</li>
<li>
<p><code>java.util.Calendar</code></p>
</li>
<li>
<p><code>java.sql.Date</code></p>
</li>
<li>
<p><code>java.sql.Time</code></p>
</li>
<li>
<p><code>java.sql.Timestamp</code></p>
</li>
</ul>
</div>
<div id="mapping-generated-CreationTimestamp-example" class="exampleblock">
<div class="title">Example 61. <code>@CreationTimestamp</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Event")
public static class Event {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`timestamp`")
    @CreationTimestamp
    private Date timestamp;

    public Event() {}

    public Long getId() {
        return id;
    }

    public Date getTimestamp() {
        return timestamp;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When the <code>Event</code> entity is persisted, Hibernate is going to populate the underlying <code>timestamp</code> column with the current JVM timestamp value:</p>
</div>
<div id="mapping-generated-CreationTimestamp-persist-example" class="exampleblock">
<div class="title">Example 62. <code>@CreationTimestamp</code> persist example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Event dateEvent = new Event( );
entityManager.persist( dateEvent );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Event("timestamp", id)
VALUES (?, ?)

-- binding parameter [1] as [TIMESTAMP] - [Tue Nov 15 16:24:20 EET 2016]
-- binding parameter [2] as [BIGINT]    - [1]</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="mapping-generated-ValueGenerationType"><code>@ValueGenerationType</code> meta-annotation</h5>
<div class="paragraph">
<p>Hibernate 4.3 introduced the <code>@ValueGenerationType</code> meta-annotation, which is a new approach to declaring generated attributes or customizing generators.</p>
</div>
<div class="paragraph">
<p><code>@Generated</code> has been retrofitted to use the <code>@ValueGenerationType</code> meta-annotation.
But <code>@ValueGenerationType</code> exposes more features than what <code>@Generated</code> currently supports, and,
to leverage some of those features, you&#8217;d simply wire up a new generator annotation.</p>
</div>
<div class="paragraph">
<p>As you&#8217;ll see in the following examples, the <code>@ValueGenerationType</code> meta-annotation is used when declaring the custom annotation used to mark the entity properties that need a specific generation strategy.
The actual generation logic must be implemented in class that implements the <code>AnnotationValueGeneration</code> interface.</p>
</div>
<div class="sect5">
<h6 id="mapping-database-generated-value">Database-generated values</h6>
<div class="paragraph">
<p>For example, let&#8217;s say we want the timestamps to be generated by calls to the standard ANSI SQL function <code>current_timestamp</code> (rather than triggers or DEFAULT values):</p>
</div>
<div id="mapping-database-generated-value-example" class="exampleblock">
<div class="title">Example 63. A <code>ValueGenerationType</code> mapping for database generation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Event")
public static class Event {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`timestamp`")
    @FunctionCreationTimestamp
    private Date timestamp;

    public Event() {}

    public Long getId() {
        return id;
    }

    public Date getTimestamp() {
        return timestamp;
    }
}

@ValueGenerationType(generatedBy = FunctionCreationValueGeneration.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface FunctionCreationTimestamp {}

public static class FunctionCreationValueGeneration
        implements AnnotationValueGeneration&lt;FunctionCreationTimestamp&gt; {

    @Override
    public void initialize(FunctionCreationTimestamp annotation, Class&lt;?&gt; propertyType) {
    }

    /**
     * Generate value on INSERT
     * @return when to generate the value
     */
    public GenerationTiming getGenerationTiming() {
        return GenerationTiming.INSERT;
    }

    /**
     * Returns null because the value is generated by the database.
     * @return null
     */
    public ValueGenerator&lt;?&gt; getValueGenerator() {
        return null;
    }

    /**
     * Returns true because the value is generated by the database.
     * @return true
     */
    public boolean referenceColumnInSql() {
        return true;
    }

    /**
     * Returns the database-generated value
     * @return database-generated value
     */
    public String getDatabaseGeneratedReferencedColumnValue() {
        return "current_timestamp";
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When persisting an <code>Event</code> entity, Hibernate generates the following SQL statement:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Event ("timestamp", id)
VALUES (current_timestamp, 1)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see, the <code>current_timestamp</code> value was used for assigning the <code>timestamp</code> column value.</p>
</div>
</div>
<div class="sect5">
<h6 id="mapping-in-memory-generated-value">In-memory-generated values</h6>
<div class="paragraph">
<p>If the timestamp value needs to be generated in-memory, the following mapping must be used instead:</p>
</div>
<div id="mapping-in-memory-generated-value-example" class="exampleblock">
<div class="title">Example 64. A <code>ValueGenerationType</code> mapping for in-memory value generation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Event")
public static class Event {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`timestamp`")
    @FunctionCreationTimestamp
    private Date timestamp;

    public Event() {}

    public Long getId() {
        return id;
    }

    public Date getTimestamp() {
        return timestamp;
    }
}

@ValueGenerationType(generatedBy = FunctionCreationValueGeneration.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface FunctionCreationTimestamp {}

public static class FunctionCreationValueGeneration
        implements AnnotationValueGeneration&lt;FunctionCreationTimestamp&gt; {

    @Override
    public void initialize(FunctionCreationTimestamp annotation, Class&lt;?&gt; propertyType) {
    }

    /**
     * Generate value on INSERT
     * @return when to generate the value
     */
    public GenerationTiming getGenerationTiming() {
        return GenerationTiming.INSERT;
    }

    /**
     * Returns the in-memory generated value
     * @return {@code true}
     */
    public ValueGenerator&lt;?&gt; getValueGenerator() {
        return (session, owner) -&gt; new Date( );
    }

    /**
     * Returns false because the value is generated by the database.
     * @return false
     */
    public boolean referenceColumnInSql() {
        return false;
    }

    /**
     * Returns null because the value is generated in-memory.
     * @return null
     */
    public String getDatabaseGeneratedReferencedColumnValue() {
        return null;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When persisting an <code>Event</code> entity, Hibernate generates the following SQL statement:</p>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Event ("timestamp", id)
VALUES ('Tue Mar 01 10:58:18 EET 2016', 1)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see, the <code>new Date()</code> object value was used for assigning the <code>timestamp</code> column value.</p>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-column-read-and-write">Column transformers: read and write expressions</h4>
<div class="paragraph">
<p>Hibernate allows you to customize the SQL it uses to read and write the values of columns mapped to <code>@Basic</code> types.
For example, if your database provides a set of data encryption functions, you can invoke them for individual columns like in the following example.</p>
</div>
<div id="mapping-column-read-and-write-example" class="exampleblock">
<div class="title">Example 65. <code>@ColumnTransformer</code> example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Employee")
public static class Employee {

    @Id
    private Long id;

    @NaturalId
    private String username;

    @Column(name = "pswd")
    @ColumnTransformer(
        read = "decrypt( 'AES', '00', pswd  )",
        write = "encrypt('AES', '00', ?)"
    )
    private String password;

    private int accessLevel;

    @ManyToOne(fetch = FetchType.LAZY)
    private Department department;

    @ManyToMany(mappedBy = "employees")
    private List&lt;Project&gt; projects = new ArrayList&lt;&gt;();

    //Getters and setters omitted for brevity
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>You can use the plural form <code>@ColumnTransformers</code> if more than one columns need to define either of these rules.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>If a property uses more than one column, you must use the <code>forColumn</code> attribute to specify which column, the expressions are targeting.</p>
</div>
<div id="mapping-column-read-and-write-composite-type-example" class="exampleblock">
<div class="title">Example 66. <code>@ColumnTransformer</code> <code>forColumn</code> attribute usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Savings")
public static class Savings {

    @Id
    private Long id;

    @Type(type = "org.hibernate.userguide.mapping.basic.MonetaryAmountUserType")
    @Columns(columns = {
        @Column(name = "money"),
        @Column(name = "currency")
    })
    @ColumnTransformer(
        forColumn = "money",
        read = "money / 100",
        write = "? * 100"
    )
    private MonetaryAmount wallet;

    //Getters and setters omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Hibernate applies the custom expressions automatically whenever the property is referenced in a query.
This functionality is similar to a derived-property <a href="#mapping-column-formula"><code>@Formula</code></a> with two differences:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The property is backed by one or more columns that are exported as part of automatic schema generation.</p>
</li>
<li>
<p>The property is read-write, not read-only.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The <code>write</code> expression, if specified, must contain exactly one '?' placeholder for the value.</p>
</div>
<div id="mapping-column-read-and-write-composite-type-persistence-example" class="exampleblock">
<div class="title">Example 67. Persisting an entity with a <code>@ColumnTransformer</code> and a composite type</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Savings savings = new Savings( );
    savings.setId( 1L );
    savings.setWallet( new MonetaryAmount( BigDecimal.TEN, Currency.getInstance( Locale.US ) ) );
    entityManager.persist( savings );
} );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Savings savings = entityManager.find( Savings.class, 1L );
    assertEquals( 10, savings.getWallet().getAmount().intValue());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Savings (money, currency, id)
VALUES (10 * 100, 'USD', 1)

SELECT
    s.id as id1_0_0_,
    s.money / 100 as money2_0_0_,
    s.currency as currency3_0_0_
FROM
    Savings s
WHERE
    s.id = 1</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-column-formula"><code>@Formula</code></h4>
<div class="paragraph">
<p>Sometimes, you want the Database to do some computation for you rather than in the JVM, you might also create some kind of virtual column.
You can use a SQL fragment (aka formula) instead of mapping a property into a column. This kind of property is read only (its value is calculated by your formula fragment)</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>You should be aware that the <code>@Formula</code> annotation takes a native SQL clause which can affect database portability.</p>
</div>
</td>
</tr>
</table>
</div>
<div id="mapping-column-formula-example" class="exampleblock">
<div class="title">Example 68. <code>@Formula</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Account")
public static class Account {

    @Id
    private Long id;

    private Double credit;

    private Double rate;

    @Formula(value = "credit * rate")
    private Double interest;

    //Getters and setters omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When loading the <code>Account</code> entity, Hibernate is going to calculate the <code>interest</code> property using the configured <code>@Formula</code>:</p>
</div>
<div id="mapping-column-formula-persistence-example" class="exampleblock">
<div class="title">Example 69. Persisting an entity with a <code>@Formula</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Account account = new Account( );
    account.setId( 1L );
    account.setCredit( 5000d );
    account.setRate( 1.25 / 100 );
    entityManager.persist( account );
} );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Account account = entityManager.find( Account.class, 1L );
    assertEquals( Double.valueOf( 62.5d ), account.getInterest());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Account (credit, rate, id)
VALUES (5000.0, 0.0125, 1)

SELECT
    a.id as id1_0_0_,
    a.credit as credit2_0_0_,
    a.rate as rate3_0_0_,
    a.credit * a.rate as formula0_0_
FROM
    Account a
WHERE
    a.id = 1</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The SQL fragment can be as complex as you want and even include subselects.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="mapping-column-where"><code>@Where</code></h4>
<div class="paragraph">
<p>Sometimes, you want to filter out entities or collections using a custom SQL criteria.
This can be achieved using the <code>@Where</code> annotation, which can be applied to entities and collections.</p>
</div>
<div id="mapping-where-example" class="exampleblock">
<div class="title">Example 70. <code>@Where</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public enum AccountType {
    DEBIT,
    CREDIT
}

@Entity(name = "Client")
public static class Client {

    @Id
    private Long id;

    private String name;

    @Where( clause = "account_type = 'DEBIT'")
    @OneToMany(mappedBy = "client")
    private List&lt;Account&gt; debitAccounts = new ArrayList&lt;&gt;( );

    @Where( clause = "account_type = 'CREDIT'")
    @OneToMany(mappedBy = "client")
    private List&lt;Account&gt; creditAccounts = new ArrayList&lt;&gt;( );

    //Getters and setters omitted for brevity

}

@Entity(name = "Account")
@Where( clause = "active = true" )
public static class Account {

    @Id
    private Long id;

    @ManyToOne
    private Client client;

    @Column(name = "account_type")
    @Enumerated(EnumType.STRING)
    private AccountType type;

    private Double amount;

    private Double rate;

    private boolean active;

    //Getters and setters omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>If the database contains the following entities:</p>
</div>
<div id="mapping-where-persistence-example" class="exampleblock">
<div class="title">Example 71. Persisting an fetching entities with a <code>@Where</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {

    Client client = new Client();
    client.setId( 1L );
    client.setName( "John Doe" );
    entityManager.persist( client );

    Account account1 = new Account( );
    account1.setId( 1L );
    account1.setType( AccountType.CREDIT );
    account1.setAmount( 5000d );
    account1.setRate( 1.25 / 100 );
    account1.setActive( true );
    account1.setClient( client );
    client.getCreditAccounts().add( account1 );
    entityManager.persist( account1 );

    Account account2 = new Account( );
    account2.setId( 2L );
    account2.setType( AccountType.DEBIT );
    account2.setAmount( 0d );
    account2.setRate( 1.05 / 100 );
    account2.setActive( false );
    account2.setClient( client );
    client.getDebitAccounts().add( account2 );
    entityManager.persist( account2 );

    Account account3 = new Account( );
    account3.setType( AccountType.DEBIT );
    account3.setId( 3L );
    account3.setAmount( 250d );
    account3.setRate( 1.05 / 100 );
    account3.setActive( true );
    account3.setClient( client );
    client.getDebitAccounts().add( account3 );
    entityManager.persist( account3 );
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Client (name, id)
VALUES ('John Doe', 1)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (true, 5000.0, 1, 0.0125, 'CREDIT', 1)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (false, 0.0, 1, 0.0105, 'DEBIT', 2)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (true, 250.0, 1, 0.0105, 'DEBIT', 3)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When executing an <code>Account</code> entity query, Hibernate is going to filter out all records that are not active.</p>
</div>
<div id="mapping-where-entity-query-example" class="exampleblock">
<div class="title">Example 72. Query entities mapped with <code>@Where</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    List&lt;Account&gt; accounts = entityManager.createQuery(
        "select a from Account a", Account.class)
    .getResultList();
    assertEquals( 2, accounts.size());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT
    a.id as id1_0_,
    a.active as active2_0_,
    a.amount as amount3_0_,
    a.client_id as client_i6_0_,
    a.rate as rate4_0_,
    a.account_type as account_5_0_
FROM
    Account a
WHERE ( a.active = true )</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When fetching the <code>debitAccounts</code> or the <code>creditAccounts</code> collections, Hibernate is going to apply the <code>@Where</code> clause filtering criteria to the associated child entities.</p>
</div>
<div id="mapping-where-collection-query-example" class="exampleblock">
<div class="title">Example 73. Traversing collections mapped with <code>@Where</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Client client = entityManager.find( Client.class, 1L );
    assertEquals( 1, client.getCreditAccounts().size() );
    assertEquals( 1, client.getDebitAccounts().size() );
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT
    c.client_id as client_i6_0_0_,
    c.id as id1_0_0_,
    c.id as id1_0_1_,
    c.active as active2_0_1_,
    c.amount as amount3_0_1_,
    c.client_id as client_i6_0_1_,
    c.rate as rate4_0_1_,
    c.account_type as account_5_0_1_
FROM
    Account c
WHERE ( c.active = true and c.account_type = 'CREDIT' ) AND c.client_id = 1

SELECT
    d.client_id as client_i6_0_0_,
    d.id as id1_0_0_,
    d.id as id1_0_1_,
    d.active as active2_0_1_,
    d.amount as amount3_0_1_,
    d.client_id as client_i6_0_1_,
    d.rate as rate4_0_1_,
    d.account_type as account_5_0_1_
FROM
    Account d
WHERE ( d.active = true and d.account_type = 'DEBIT' ) AND d.client_id = 1</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-column-filter"><code>@Filter</code></h4>
<div class="paragraph">
<p>The <code>@Filter</code> annotation is another way to filter out entities or collections using a custom SQL criteria, for both entities and collections.
Unlike the <code>@Where</code> annotation, <code>@Filter</code> allows you to parameterize the filter clause at runtime.</p>
</div>
<div id="mapping-filter-example" class="exampleblock">
<div class="title">Example 74. <code>@Filter</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public enum AccountType {
    DEBIT,
    CREDIT
}

@Entity(name = "Client")
public static class Client {

    @Id
    private Long id;

    private String name;

    @OneToMany(mappedBy = "client")
    @Filter(name="activeAccount", condition="active = :active")
    private List&lt;Account&gt; accounts = new ArrayList&lt;&gt;( );

    //Getters and setters omitted for brevity

}

@Entity(name = "Account")
@FilterDef(name="activeAccount", parameters=@ParamDef( name="active", type="boolean" ) )
@Filter(name="activeAccount", condition="active = :active")
public static class Account {

    @Id
    private Long id;

    @ManyToOne
    private Client client;

    @Column(name = "account_type")
    @Enumerated(EnumType.STRING)
    private AccountType type;

    private Double amount;

    private Double rate;

    private boolean active;

    //Getters and setters omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>If the database contains the following entities:</p>
</div>
<div id="mapping-filter-persistence-example" class="exampleblock">
<div class="title">Example 75. Persisting an fetching entities with a <code>@Filter</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {

    Client client = new Client();
    client.setId( 1L );
    client.setName( "John Doe" );
    entityManager.persist( client );

    Account account1 = new Account( );
    account1.setId( 1L );
    account1.setType( AccountType.CREDIT );
    account1.setAmount( 5000d );
    account1.setRate( 1.25 / 100 );
    account1.setActive( true );
    account1.setClient( client );
    client.getAccounts().add( account1 );
    entityManager.persist( account1 );

    Account account2 = new Account( );
    account2.setId( 2L );
    account2.setType( AccountType.DEBIT );
    account2.setAmount( 0d );
    account2.setRate( 1.05 / 100 );
    account2.setActive( false );
    account2.setClient( client );
    client.getAccounts().add( account2 );
    entityManager.persist( account2 );

    Account account3 = new Account( );
    account3.setType( AccountType.DEBIT );
    account3.setId( 3L );
    account3.setAmount( 250d );
    account3.setRate( 1.05 / 100 );
    account3.setActive( true );
    account3.setClient( client );
    client.getAccounts().add( account3 );
    entityManager.persist( account3 );
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Client (name, id)
VALUES ('John Doe', 1)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (true, 5000.0, 1, 0.0125, 'CREDIT', 1)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (false, 0.0, 1, 0.0105, 'DEBIT', 2)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (true, 250.0, 1, 0.0105, 'DEBIT', 3)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>By default, without explicitly enabling the filter, Hibernate is going to fetch all <code>Account</code> entities.
If the filter is enabled and the filter parameter value is provided,
then Hibernate is going to apply the filtering criteria to the associated <code>Account</code> entities.</p>
</div>
<div id="mapping-filter-entity-query-example" class="exampleblock">
<div class="title">Example 76. Query entities mapped with <code>@Filter</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    List&lt;Account&gt; accounts = entityManager.createQuery(
        "select a from Account a", Account.class)
    .getResultList();
    assertEquals( 3, accounts.size());
} );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    log.infof( "Activate filter [%s]", "activeAccount");

    entityManager
        .unwrap( Session.class )
        .enableFilter( "activeAccount" )
        .setParameter( "active", true);

    List&lt;Account&gt; accounts = entityManager.createQuery(
        "select a from Account a", Account.class)
    .getResultList();
    assertEquals( 2, accounts.size());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT
    a.id as id1_0_,
    a.active as active2_0_,
    a.amount as amount3_0_,
    a.client_id as client_i6_0_,
    a.rate as rate4_0_,
    a.account_type as account_5_0_
FROM
    Account a

-- Activate filter [activeAccount]

SELECT
    a.id as id1_0_,
    a.active as active2_0_,
    a.amount as amount3_0_,
    a.client_id as client_i6_0_,
    a.rate as rate4_0_,
    a.account_type as account_5_0_
FROM
    Account a
WHERE
    a.active = true</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Filters apply to entity queries, but not to direct fetching.
Therefore, in the following example, the filter is not taken into consideration when fetching an entity from the Persistence Context.</p>
</div>
<div id="mapping-filter-entity-example" class="listingblock">
<div class="title">Fetching entities mapped with <code>@Filter</code></div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    log.infof( "Activate filter [%s]", "activeAccount");

    entityManager
        .unwrap( Session.class )
        .enableFilter( "activeAccount" )
        .setParameter( "active", true);

    Account account = entityManager.find( Account.class, 2L );
    assertFalse( account.isActive() );
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT
    a.id as id1_0_0_,
    a.active as active2_0_0_,
    a.amount as amount3_0_0_,
    a.client_id as client_i6_0_0_,
    a.rate as rate4_0_0_,
    a.account_type as account_5_0_0_,
    c.id as id1_1_1_,
    c.name as name2_1_1_
FROM
    Account a
LEFT OUTER JOIN
    Client c
        ON a.client_id=c.id
WHERE
    a.id = 2</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see from the example above, contrary to an entity query, the filter does not prevent the entity from being loaded.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Just like with entity queries, collections can be filtered as well, but only if the filter is explicitly enabled on the currently running Hibernate <code>Session</code>.
This way, when fetching the <code>accounts</code> collections, Hibernate is going to apply the <code>@Filter</code> clause filtering criteria to the associated collection entries.</p>
</div>
<div id="mapping-filter-collection-query-example" class="exampleblock">
<div class="title">Example 77. Traversing collections mapped with <code>@Filter</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Client client = entityManager.find( Client.class, 1L );
    assertEquals( 3, client.getAccounts().size() );
} );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    log.infof( "Activate filter [%s]", "activeAccount");

    entityManager
        .unwrap( Session.class )
        .enableFilter( "activeAccount" )
        .setParameter( "active", true);

    Client client = entityManager.find( Client.class, 1L );
    assertEquals( 2, client.getAccounts().size() );
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT
    c.id as id1_1_0_,
    c.name as name2_1_0_
FROM
    Client c
WHERE
    c.id = 1

SELECT
    a.id as id1_0_,
    a.active as active2_0_,
    a.amount as amount3_0_,
    a.client_id as client_i6_0_,
    a.rate as rate4_0_,
    a.account_type as account_5_0_
FROM
    Account a
WHERE
    a.client_id = 1

-- Activate filter [activeAccount]

SELECT
    c.id as id1_1_0_,
    c.name as name2_1_0_
FROM
    Client c
WHERE
    c.id = 1

SELECT
    a.id as id1_0_,
    a.active as active2_0_,
    a.amount as amount3_0_,
    a.client_id as client_i6_0_,
    a.rate as rate4_0_,
    a.account_type as account_5_0_
FROM
    Account a
WHERE
    accounts0_.active = true
    and a.client_id = 1</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The main advantage of <code>@Filter</code> over the <code>@Where</code> clause is that the filtering criteria can be customized at runtime.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
<div class="paragraph">
<p>It&#8217;s not possible to combine the <code>@Filter</code> and <code>@Cache</code> collection annotations.
This limitation is due to ensuring consistency and because the filtering information is not stored in the second-level cache.</p>
</div>
<div class="paragraph">
<p>If caching was allowed for a currently filtered collection, then the second-level cache would store only a subset of the whole collection.
Afterward, every other Session will get the filtered collection from the cache, even if the Session-level filters have not been explicitly activated.</p>
</div>
<div class="paragraph">
<p>For this reason, the second-level collection cache is limited to storing whole collections, and not subsets.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="mapping-column-filter-join-table"><code>@FilterJoinTable</code></h4>
<div class="paragraph">
<p>When using the <code>@Filter</code> annotation with collections, the filtering is done against the child entries (entities or embeddables).
However, if you have a link table between the parent entity and the child table, then you need to use the <code>@FilterJoinTable</code> to filter child entries according to some column contained in the join table.</p>
</div>
<div class="paragraph">
<p>The <code>@FilterJoinTable</code> annotation can be, therefore, applied to a unidirectional <code>@OneToMany</code> collection as illustrate din the following mapping:</p>
</div>
<div id="mapping-filter-join-table-example" class="exampleblock">
<div class="title">Example 78. <code>@FilterJoinTable</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public enum AccountType {
    DEBIT,
    CREDIT
}

@Entity(name = "Client")
@FilterDef(name="firstAccounts", parameters=@ParamDef( name="maxOrderId", type="int" ) )
@Filter(name="firstAccounts", condition="order_id &lt;= :maxOrderId")
public static class Client {

    @Id
    private Long id;

    private String name;

    @OneToMany
    @OrderColumn(name = "order_id")
    @FilterJoinTable(name="firstAccounts", condition="order_id &lt;= :maxOrderId")
    private List&lt;Account&gt; accounts = new ArrayList&lt;&gt;( );

    //Getters and setters omitted for brevity

}

@Entity(name = "Account")
public static class Account {

    @Id
    private Long id;

    @Column(name = "account_type")
    @Enumerated(EnumType.STRING)
    private AccountType type;

    private Double amount;

    private Double rate;

    private boolean active;

    //Getters and setters omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>If the database contains the following entities:</p>
</div>
<div id="mapping-filter-join-table-persistence-example" class="exampleblock">
<div class="title">Example 79. Persisting an fetching entities with a <code>@FilterJoinTable</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {

    Client client = new Client();
    client.setId( 1L );
    client.setName( "John Doe" );
    entityManager.persist( client );

    Account account1 = new Account( );
    account1.setId( 1L );
    account1.setType( AccountType.CREDIT );
    account1.setAmount( 5000d );
    account1.setRate( 1.25 / 100 );
    account1.setActive( true );
    client.getAccounts().add( account1 );
    entityManager.persist( account1 );

    Account account2 = new Account( );
    account2.setId( 2L );
    account2.setType( AccountType.DEBIT );
    account2.setAmount( 0d );
    account2.setRate( 1.05 / 100 );
    account2.setActive( false );
    client.getAccounts().add( account2 );
    entityManager.persist( account2 );

    Account account3 = new Account( );
    account3.setType( AccountType.DEBIT );
    account3.setId( 3L );
    account3.setAmount( 250d );
    account3.setRate( 1.05 / 100 );
    account3.setActive( true );
    client.getAccounts().add( account3 );
    entityManager.persist( account3 );
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO Client (name, id)
VALUES ('John Doe', 1)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (true, 5000.0, 1, 0.0125, 'CREDIT', 1)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (false, 0.0, 1, 0.0105, 'DEBIT', 2)

INSERT INTO Account (active, amount, client_id, rate, account_type, id)
VALUES (true, 250.0, 1, 0.0105, 'DEBIT', 3)

INSERT INTO Client_Account (Client_id, order_id, accounts_id)
VALUES (1, 0, 1)

INSERT INTO Client_Account (Client_id, order_id, accounts_id)
VALUES (1, 0, 1)

INSERT INTO Client_Account (Client_id, order_id, accounts_id)
VALUES (1, 1, 2)

INSERT INTO Client_Account (Client_id, order_id, accounts_id)
VALUES (1, 2, 3)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The collections can be filtered if the associated filter is enabled on the currently running Hibernate <code>Session</code>.
This way, when fetching the <code>accounts</code> collections, Hibernate is going to apply the <code>@FilterJoinTable</code> clause filtering criteria to the associated collection entries.</p>
</div>
<div id="mapping-filter-collection-query-example" class="exampleblock">
<div class="title">Example 80. Traversing collections mapped with <code>@FilterJoinTable</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Client client = entityManager.find( Client.class, 1L );
    assertEquals( 3, client.getAccounts().size());
} );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    log.infof( "Activate filter [%s]", "firstAccounts");

    Client client = entityManager.find( Client.class, 1L );

    entityManager
        .unwrap( Session.class )
        .enableFilter( "firstAccounts" )
        .setParameter( "maxOrderId", 1);

    assertEquals( 2, client.getAccounts().size());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT
    ca.Client_id as Client_i1_2_0_,
    ca.accounts_id as accounts2_2_0_,
    ca.order_id as order_id3_0_,
    a.id as id1_0_1_,
    a.active as active2_0_1_,
    a.amount as amount3_0_1_,
    a.rate as rate4_0_1_,
    a.account_type as account_5_0_1_
FROM
    Client_Account ca
INNER JOIN
    Account a
ON  ca.accounts_id=a.id
WHERE
    ca.Client_id = ?

-- binding parameter [1] as [BIGINT] - [1]

-- Activate filter [firstAccounts]

SELECT
    ca.Client_id as Client_i1_2_0_,
    ca.accounts_id as accounts2_2_0_,
    ca.order_id as order_id3_0_,
    a.id as id1_0_1_,
    a.active as active2_0_1_,
    a.amount as amount3_0_1_,
    a.rate as rate4_0_1_,
    a.account_type as account_5_0_1_
FROM
    Client_Account ca
INNER JOIN
    Account a
ON  ca.accounts_id=a.id
WHERE
    ca.order_id &lt;= ?
    AND ca.Client_id = ?

-- binding parameter [1] as [INTEGER] - [1]
-- binding parameter [2] as [BIGINT] - [1]</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-column-any"><code>@Any</code> mapping</h4>
<div class="paragraph">
<p>There is one more type of property mapping.
The <code>@Any</code> mapping defines a polymorphic association to classes from multiple tables.
This type of mapping requires more than one column.
The first column contains the type of the associated entity.
The remaining columns contain the identifier.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>It is impossible to specify a foreign key constraint for this kind of association.
This is not the usual way of mapping polymorphic associations and you should use this only in special cases (e.g. audit logs, user session data, etc).</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The <code>@Any</code> annotation describes the column holding the metadata information.
To link the value of the metadata information and an actual entity type, the <code>@AnyDef</code> and <code>@AnyDefs</code> annotations are used.
The <code>metaType</code> attribute allows the application to specify a custom type that maps database column values to persistent classes that have identifier properties of the type specified by <code>idType</code>.
You must specify the mapping from values of the <code>metaType</code> to class names.</p>
</div>
<div class="paragraph">
<p>For the next examples, consider the following <code>Property</code> class hierarchy:</p>
</div>
<div id="mapping-column-any-property-example" class="exampleblock">
<div class="title">Example 81. <code>Property</code> class hierarchy</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">public interface Property&lt;T&gt; {

    String getName();

    T getValue();
}


@Entity
@Table(name="integer_property")
public class IntegerProperty implements Property&lt;Integer&gt; {

    @Id
    private Long id;

    @Column(name = "`name`")
    private String name;

    @Column(name = "`value`")
    private Integer value;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }
}


@Entity
@Table(name="string_property")
public class StringProperty implements Property&lt;String&gt; {

    @Id
    private Long id;

    @Column(name = "`name`")
    private String name;

    @Column(name = "`value`")
    private String value;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>A <code>PropertyHolder</code> can reference any such property, and, because each <code>Property</code> belongs to a separate table, the <code>@Any</code> annotation is, therefore, required.</p>
</div>
<div id="mapping-column-any-example" class="exampleblock">
<div class="title">Example 82. <code>@Any</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity
@Table( name = "property_holder" )
public class PropertyHolder {

    @Id
    private Long id;

    @Any(
        metaDef = "PropertyMetaDef",
        metaColumn = @Column( name = "property_type" )
    )
    @JoinColumn( name = "property_id" )
    private Property property;

	//Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">CREATE TABLE property_holder (
    id BIGINT NOT NULL,
    property_type VARCHAR(255),
    property_id BIGINT,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see, there are two columns used to reference a <code>Property</code> instance: <code>property_id</code> and <code>property_type</code>.
The <code>property_id</code> is used to match the <code>id</code> column of either the <code>string_property</code> or <code>integer_property</code> tables,
while the <code>property_type</code> is used to match the <code>string_property</code> or the  <code>integer_property</code> table.</p>
</div>
<div class="paragraph">
<p>The table resolving mapping is defined by the <code>metaDef</code> attribute which references an <code>@AnyMetaDef</code> mapping.
Although the <code>@AnyMetaDef</code> mapping could be set right next to the <code>@Any</code> annotation,
it&#8217;s good practice to reuse it, therefore it makes sense to configure it on a class or package-level basis.</p>
</div>
<div class="paragraph">
<p>The <code>package-info.java</code> contains the <code>@AnyMetaDef</code> mapping:</p>
</div>
<div id="mapping-column-any-meta-def-example" class="exampleblock">
<div class="title">Example 83. <code>@Any</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@AnyMetaDef( name= "PropertyMetaDef", metaType = "string", idType = "long",
    metaValues = {
            @MetaValue(value = "S", targetEntity = StringProperty.class),
            @MetaValue(value = "I", targetEntity = IntegerProperty.class)
        }
    )
package org.hibernate.userguide.mapping.basic.any;

import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.MetaValue;</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>It is recommended to place the <code>@AnyMetaDef</code> mapping as a package metadata.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To see how the <code>@Any</code> annotation in action, consider the following example:</p>
</div>
<div id="mapping-column-any-persistence-example" class="exampleblock">
<div class="title">Example 84. <code>@Any</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInHibernate( this::sessionFactory, session -&gt; {
    IntegerProperty ageProperty = new IntegerProperty();
    ageProperty.setId( 1L );
    ageProperty.setName( "age" );
    ageProperty.setValue( 23 );

    StringProperty nameProperty = new StringProperty();
    nameProperty.setId( 1L );
    nameProperty.setName( "name" );
    nameProperty.setValue( "John Doe" );

    session.persist( ageProperty );
    session.persist( nameProperty );

    PropertyHolder namePropertyHolder = new PropertyHolder();
    namePropertyHolder.setId( 1L );
    namePropertyHolder.setProperty( nameProperty );
    session.persist( namePropertyHolder );
} );

doInHibernate( this::sessionFactory, session -&gt; {
    PropertyHolder propertyHolder = session.get( PropertyHolder.class, 1L );
    assertEquals("name", propertyHolder.getProperty().getName());
    assertEquals("John Doe", propertyHolder.getProperty().getValue());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO integer_property
       ( "name", "value", id )
VALUES ( 'age', 23, 1 )

INSERT INTO string_property
       ( "name", "value", id )
VALUES ( 'name', 'John Doe', 1 )

INSERT INTO property_holder
       ( property_type, property_id, id )
VALUES ( 'S', 1, 1 )


SELECT ph.id AS id1_1_0_,
       ph.property_type AS property2_1_0_,
       ph.property_id AS property3_1_0_
FROM   property_holder ph
WHERE  ph.id = 1


SELECT sp.id AS id1_2_0_,
       sp."name" AS name2_2_0_,
       sp."value" AS value3_2_0_
FROM   string_property sp
WHERE  sp.id = 1</code></pre>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="mapping-column-many-to-any"><code>@ManyToAny</code> mapping</h5>
<div class="paragraph">
<p>The <code>@Any</code> mapping is useful to emulate a <code>@ManyToOne</code> association when there can be multiple target entities.
To emulate a <code>@OneToMany</code> association, the <code>@ManyToAny</code> annotation must be used.</p>
</div>
<div class="paragraph">
<p>In the following example, the <code>PropertyRepository</code> entity has a collection of <code>Property</code> entities.
The <code>repository_properties</code> link table holds the associations between <code>PropertyRepository</code> and <code>Property</code> entities.</p>
</div>
<div id="mapping-column-many-to-any-example" class="exampleblock">
<div class="title">Example 85. <code>@ManyToAny</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity
@Table( name = "property_repository" )
public class PropertyRepository {

    @Id
    private Long id;

    @ManyToAny(
        metaDef = "PropertyMetaDef",
        metaColumn = @Column( name = "property_type" )
    )
    @Cascade( { org.hibernate.annotations.CascadeType.ALL })
    @JoinTable(name = "repository_properties",
        joinColumns = @JoinColumn(name = "repository_id"),
        inverseJoinColumns = @JoinColumn(name = "property_id")
    )
    private List&lt;Property&lt;?&gt;&gt; properties = new ArrayList&lt;&gt;(  );

	//Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">CREATE TABLE property_repository (
    id BIGINT NOT NULL,
    PRIMARY KEY ( id )
)

CREATE TABLE repository_properties (
    repository_id BIGINT NOT NULL,
    property_type VARCHAR(255),
    property_id BIGINT NOT NULL
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To see how the <code>@ManyToAny</code> annotation works, consider the following example:</p>
</div>
<div id="mapping-column-many-to-any-persistence-example" class="exampleblock">
<div class="title">Example 86. <code>@Any</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInHibernate( this::sessionFactory, session -&gt; {
    IntegerProperty ageProperty = new IntegerProperty();
    ageProperty.setId( 1L );
    ageProperty.setName( "age" );
    ageProperty.setValue( 23 );

    StringProperty nameProperty = new StringProperty();
    nameProperty.setId( 1L );
    nameProperty.setName( "name" );
    nameProperty.setValue( "John Doe" );

    session.persist( ageProperty );
    session.persist( nameProperty );

    PropertyRepository propertyRepository = new PropertyRepository();
    propertyRepository.setId( 1L );
    propertyRepository.getProperties().add( ageProperty );
    propertyRepository.getProperties().add( nameProperty );
    session.persist( propertyRepository );
} );

doInHibernate( this::sessionFactory, session -&gt; {
    PropertyRepository propertyRepository = session.get( PropertyRepository.class, 1L );
    assertEquals(2, propertyRepository.getProperties().size());
    for(Property property : propertyRepository.getProperties()) {
        assertNotNull( property.getValue() );
    }
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">INSERT INTO integer_property
       ( "name", "value", id )
VALUES ( 'age', 23, 1 )

INSERT INTO string_property
       ( "name", "value", id )
VALUES ( 'name', 'John Doe', 1 )

INSERT INTO property_repository ( id )
VALUES ( 1 )

INSERT INTO repository_properties
    ( repository_id , property_type , property_id )
VALUES
    ( 1 , 'I' , 1 )

INSERT INTO repository_properties
    ( repository_id , property_type , property_id )
VALUES
    ( 1 , 'S' , 1 )

SELECT pr.id AS id1_1_0_
FROM   property_repository pr
WHERE  pr.id = 1

SELECT ip.id AS id1_0_0_ ,
       integerpro0_."name" AS name2_0_0_ ,
       integerpro0_."value" AS value3_0_0_
FROM   integer_property integerpro0_
WHERE  integerpro0_.id = 1

SELECT sp.id AS id1_3_0_ ,
       sp."name" AS name2_3_0_ ,
       sp."value" AS value3_3_0_
FROM   string_property sp
WHERE  sp.id = 1</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-JoinFormula"><code>@JoinFormula</code> mapping</h4>
<div class="paragraph">
<p>The <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/JoinFormula.html"><code>@JoinFormula</code></a> annotation is used to customize the join between a child Foreign Key and a parent row Primary Key.</p>
</div>
<div id="mapping-JoinFormula-example" class="exampleblock">
<div class="title">Example 87. <code>@JoinFormula</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "User")
@Table(name = "users")
public static class User {

    @Id
    private Long id;

    private String firstName;

    private String lastName;

    private String phoneNumber;

    @ManyToOne
    @JoinFormula( "REGEXP_REPLACE(phoneNumber, '\\+(\\d+)-.*', '\\1')::int" )
    private Country country;

    //Getters and setters omitted for brevity

}

@Entity(name = "Country")
@Table(name = "countries")
public static class Country {

    @Id
    private Integer id;

    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( !( o instanceof Country ) ) {
            return false;
        }
        Country country = (Country) o;
        return Objects.equals( getId(), country.getId() );
    }

    @Override
    public int hashCode() {
        return Objects.hash( getId() );
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">CREATE TABLE countries (
    id int4 NOT NULL,
    name VARCHAR(255),
    PRIMARY KEY ( id )
)

CREATE TABLE users (
    id int8 NOT NULL,
    firstName VARCHAR(255),
    lastName VARCHAR(255),
    phoneNumber VARCHAR(255),
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>country</code> association in the <code>User</code> entity is mapped by the country identifier provided by the <code>phoneNumber</code> property.</p>
</div>
<div class="paragraph">
<p>Considering we have the following entities:</p>
</div>
<div id="mapping-JoinFormula-persistence-example" class="exampleblock">
<div class="title">Example 88. <code>@JoinFormula</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Country US = new Country();
US.setId( 1 );
US.setName( "United States" );

Country Romania = new Country();
Romania.setId( 40 );
Romania.setName( "Romania" );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    entityManager.persist( US );
    entityManager.persist( Romania );
} );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    User user1 = new User( );
    user1.setId( 1L );
    user1.setFirstName( "John" );
    user1.setLastName( "Doe" );
    user1.setPhoneNumber( "+1-234-5678" );
    entityManager.persist( user1 );

    User user2 = new User( );
    user2.setId( 2L );
    user2.setFirstName( "Vlad" );
    user2.setLastName( "Mihalcea" );
    user2.setPhoneNumber( "+40-123-4567" );
    entityManager.persist( user2 );
} );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When fetching the <code>User</code> entities, the <code>country</code> property is mapped by the <code>@JoinFormula</code> expression:</p>
</div>
<div id="mapping-JoinFormula-fetching-example" class="exampleblock">
<div class="title">Example 89. <code>@JoinFormula</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    log.info( "Fetch User entities" );

    User john = entityManager.find( User.class, 1L );
    assertEquals( US, john.getCountry());

    User vlad = entityManager.find( User.class, 2L );
    assertEquals( Romania, vlad.getCountry());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">-- Fetch User entities

SELECT
    u.id as id1_1_0_,
    u.firstName as firstNam2_1_0_,
    u.lastName as lastName3_1_0_,
    u.phoneNumber as phoneNum4_1_0_,
    REGEXP_REPLACE(u.phoneNumber, '\+(\d+)-.*', '\1')::int as formula1_0_,
    c.id as id1_0_1_,
    c.name as name2_0_1_
FROM
    users u
LEFT OUTER JOIN
    countries c
        ON REGEXP_REPLACE(u.phoneNumber, '\+(\d+)-.*', '\1')::int = c.id
WHERE
    u.id=?

-- binding parameter [1] as [BIGINT] - [1]

SELECT
    u.id as id1_1_0_,
    u.firstName as firstNam2_1_0_,
    u.lastName as lastName3_1_0_,
    u.phoneNumber as phoneNum4_1_0_,
    REGEXP_REPLACE(u.phoneNumber, '\+(\d+)-.*', '\1')::int as formula1_0_,
    c.id as id1_0_1_,
    c.name as name2_0_1_
FROM
    users u
LEFT OUTER JOIN
    countries c
        ON REGEXP_REPLACE(u.phoneNumber, '\+(\d+)-.*', '\1')::int = c.id
WHERE
    u.id=?

-- binding parameter [1] as [BIGINT] - [2]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Therefore, the <code>@JoinFormula</code> annotation is used to define a custom join association between the parent-child association.</p>
</div>
</div>
<div class="sect3">
<h4 id="mapping-JoinColumnOrFormula"><code>@JoinColumnOrFormula</code> mapping</h4>
<div class="paragraph">
<p>The <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/JoinColumnOrFormula.html"><code>@JoinColumnOrFormula</code></a> annotation is used to customize the join between a child Foreign Key and a parent row Primary Key when we need to tak into consideration a column value as well as a <code>@JoinFormula</code>.</p>
</div>
<div id="mapping-JoinColumnOrFormula-example" class="exampleblock">
<div class="title">Example 90. <code>@JoinColumnOrFormula</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "User")
@Table(name = "users")
public static class User {

    @Id
    private Long id;

    private String firstName;

    private String lastName;

    private String language;

    @ManyToOne
    @JoinColumnOrFormula( column =
        @JoinColumn(
            name = "language",
            referencedColumnName = "primaryLanguage",
            insertable = false,
            updatable = false
        )
    )
    @JoinColumnOrFormula( formula =
        @JoinFormula(
            value = "true",
            referencedColumnName = "is_default"
        )
    )
    private Country country;

    //Getters and setters omitted for brevity

}

@Entity(name = "Country")
@Table(name = "countries")
public static class Country implements Serializable {

    @Id
    private Integer id;

    private String name;

    private String primaryLanguage;

    @Column(name = "is_default")
    private boolean _default;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrimaryLanguage() {
        return primaryLanguage;
    }

    public void setPrimaryLanguage(String primaryLanguage) {
        this.primaryLanguage = primaryLanguage;
    }

    public boolean isDefault() {
        return _default;
    }

    public void setDefault(boolean _default) {
        this._default = _default;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( !( o instanceof Country ) ) {
            return false;
        }
        Country country = (Country) o;
        return Objects.equals( getId(), country.getId() );
    }

    @Override
    public int hashCode() {
        return Objects.hash( getId() );
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">CREATE TABLE countries (
    id INTEGER NOT NULL,
    is_default boolean,
    name VARCHAR(255),
    primaryLanguage VARCHAR(255),
    PRIMARY KEY ( id )
)

CREATE TABLE users (
    id BIGINT NOT NULL,
    firstName VARCHAR(255),
    language VARCHAR(255),
    lastName VARCHAR(255),
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>country</code> association in the <code>User</code> entity is mapped by the <code>language</code> property value and the the associated <code>Country</code> <code>is_default</code> column value.</p>
</div>
<div class="paragraph">
<p>Considering we have the following entities:</p>
</div>
<div id="mapping-JoinColumnOrFormula-persistence-example" class="exampleblock">
<div class="title">Example 91. <code>@JoinColumnOrFormula</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">Country US = new Country();
US.setId( 1 );
US.setDefault( true );
US.setPrimaryLanguage( "English" );
US.setName( "United States" );

Country Romania = new Country();
Romania.setId( 40 );
Romania.setDefault( true );
Romania.setName( "Romania" );
Romania.setPrimaryLanguage( "Romanian" );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    entityManager.persist( US );
    entityManager.persist( Romania );
} );

doInJPA( this::entityManagerFactory, entityManager -&gt; {
    User user1 = new User( );
    user1.setId( 1L );
    user1.setFirstName( "John" );
    user1.setLastName( "Doe" );
    user1.setLanguage( "English" );
    entityManager.persist( user1 );

    User user2 = new User( );
    user2.setId( 2L );
    user2.setFirstName( "Vlad" );
    user2.setLastName( "Mihalcea" );
    user2.setLanguage( "Romanian" );
    entityManager.persist( user2 );

} );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When fetching the <code>User</code> entities, the <code>country</code> property is mapped by the <code>@JoinColumnOrFormula</code> expression:</p>
</div>
<div id="mapping-JoinColumnOrFormula-fetching-example" class="exampleblock">
<div class="title">Example 92. <code>@JoinColumnOrFormula</code> mapping usage</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    log.info( "Fetch User entities" );

    User john = entityManager.find( User.class, 1L );
    assertEquals( US, john.getCountry());

    User vlad = entityManager.find( User.class, 2L );
    assertEquals( Romania, vlad.getCountry());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT
    u.id as id1_1_0_,
    u.language as language3_1_0_,
    u.firstName as firstNam2_1_0_,
    u.lastName as lastName4_1_0_,
    1 as formula1_0_,
    c.id as id1_0_1_,
    c.is_default as is_defau2_0_1_,
    c.name as name3_0_1_,
    c.primaryLanguage as primaryL4_0_1_
FROM
    users u
LEFT OUTER JOIN
    countries c
        ON u.language = c.primaryLanguage
        AND 1 = c.is_default
WHERE
    u.id = ?

-- binding parameter [1] as [BIGINT] - [1]

SELECT
    u.id as id1_1_0_,
    u.language as language3_1_0_,
    u.firstName as firstNam2_1_0_,
    u.lastName as lastName4_1_0_,
    1 as formula1_0_,
    c.id as id1_0_1_,
    c.is_default as is_defau2_0_1_,
    c.name as name3_0_1_,
    c.primaryLanguage as primaryL4_0_1_
FROM
    users u
LEFT OUTER JOIN
    countries c
        ON u.language = c.primaryLanguage
        AND 1 = c.is_default
WHERE
    u.id = ?

-- binding parameter [1] as [BIGINT] - [2]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Therefore, the <code>@JoinColumnOrFormula</code> annotation is used to define a custom join association between the parent-child association.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="embeddables">Embeddable types</h3>
<div class="paragraph">
<p>Historically Hibernate called these components.
JPA calls them embeddables.
Either way the concept is the same: a composition of values.
For example we might have a Name class that is a composition of first-name and last-name, or an Address class that is a composition of street, city, postal code, etc.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="title">Usage of the word <em>embeddable</em></div>
<div class="paragraph">
<p>To avoid any confusion with the annotation that marks a given embeddable type, the annotation will be further referred as <code>@Embeddable</code>.</p>
</div>
<div class="paragraph">
<p>Throughout this chapter and thereafter, for brevity sake, embeddable types may also be referred as <em>embeddable</em>.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="exampleblock">
<div class="title">Example 93. Simple embeddable type example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Embeddable
public class Name {

    private String firstName;

    private String middleName;

    private String lastName;

    ...
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Embeddable
public class Address {

    private String line1;

    private String line2;

    @Embedded
    private ZipCode zipCode;

    ...

    @Embeddable
    public static class Zip {

        private String postalCode;

        private String plus4;

        ...
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>An embeddable type is another form of value type, and its lifecycle is bound to a parent entity type, therefore inheriting the attribute access from its parent (for details on attribute access, see <a href="chapters/domain/entity.html#access-embeddable-types">Access strategies</a>).</p>
</div>
<div class="paragraph">
<p>Embeddable types can be made up of basic values as well as associations, with the caveat that, when used as collection elements, they cannot define collections themselves.</p>
</div>
<div class="sect3">
<h4 id="_component_embedded">Component / Embedded</h4>
<div class="paragraph">
<p>Most often, embeddable types are used to group multiple basic type mappings and reuse them across several entities.</p>
</div>
<div class="exampleblock">
<div class="title">Example 94. Simple Embeddedable</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Person {

    @Id
    private Integer id;

    @Embedded
    private Name name;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>JPA defines two terms for working with an embeddable type: <code>@Embeddable</code> and <code>@Embedded</code>.
<code>@Embeddable</code> is used to describe the mapping type itself (e.g. <code>Name</code>).
<code>@Embedded</code> is for referencing a given embeddable type (e.g. <code>person.name</code>).</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>So, the embeddable type is represented by the <code>Name</code> class and the parent makes use of it through the <code>person.name</code> object composition.</p>
</div>
<div class="exampleblock">
<div class="title">Example 95. Person table</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">create table Person (
    id integer not null,
    firstName VARCHAR,
    middleName VARCHAR,
    lastName VARCHAR,
    ...
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The composed values are mapped to the same table as the parent table.
Composition is part of good OO data modeling (idiomatic Java).
In fact, that table could also be mapped by the following entity type instead.</p>
</div>
<div class="exampleblock">
<div class="title">Example 96. Alternative to embeddable type composition</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Person {

    @Id
    private Integer id;

    private String firstName;

    private String middleName;

    private String lastName;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The composition form is certainly more Object-oriented, and that becomes more evident as we work with multiple embeddable types.</p>
</div>
</div>
<div class="sect3">
<h4 id="embeddable-multiple">Multiple embeddable types</h4>
<div class="exampleblock">
<div class="title">Example 97. Multiple embeddable types</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Contact {

    @Id
    private Integer id;

    @Embedded
    private Name name;

    @Embedded
    private Address homeAddress;

    @Embedded
    private Address mailingAddress;

    @Embedded
    private Address workAddress;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Although from an object-oriented perspective, it&#8217;s much more convenient to work with embeddable types, this example doesn&#8217;t work as-is.
When the same embeddable type is included multiple times in the same parent entity type, the JPA specification demands setting the associated column names explicitly.</p>
</div>
<div class="paragraph">
<p>This requirement is due to how object properties are mapped to database columns.
By default, JPA expects a database column having the same name with its associated object property.
When including multiple embeddables, the implicit name-based mapping rule doesn&#8217;t work anymore because multiple object properties could end-up being mapped to the same database column.</p>
</div>
<div class="paragraph">
<p>We have a few options to handle this issue.</p>
</div>
</div>
<div class="sect3">
<h4 id="embeddable-multiple-jpa">JPA&#8217;s AttributeOverride</h4>
<div class="paragraph">
<p>JPA defines the <code>@AttributeOverride</code> annotation to handle this scenario.</p>
</div>
<div class="exampleblock">
<div class="title">Example 98. JPA&#8217;s AttributeOverride</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Contact {

    @Id
    private Integer id;

    @Embedded
    private Name name;

    @Embedded
    @AttributeOverrides(
        @AttributeOverride(
            name = "line1",
            column = @Column( name = "home_address_line1" ),
        ),
        @AttributeOverride(
            name = "line2",
            column = @Column( name = "home_address_line2" )
        ),
        @AttributeOverride(
            name = "zipCode.postalCode",
            column = @Column( name = "home_address_postal_cd" )
        ),
        @AttributeOverride(
            name = "zipCode.plus4",
            column = @Column( name = "home_address_postal_plus4" )
        )
    )
    private Address homeAddress;

    @Embedded
    @AttributeOverrides(
        @AttributeOverride(
            name = "line1",
            column = @Column( name = "mailing_address_line1" ),
        ),
        @AttributeOverride(
            name = "line2",
            column = @Column( name = "mailing_address_line2" )
        ),
        @AttributeOverride(
            name = "zipCode.postalCode",
            column = @Column( name = "mailing_address_postal_cd" )
        ),
        @AttributeOverride(
            name = "zipCode.plus4",
            column = @Column( name = "mailing_address_postal_plus4" )
        )
    )
    private Address mailingAddress;

    @Embedded
    @AttributeOverrides(
        @AttributeOverride(
            name = "line1",
            column = @Column( name = "work_address_line1" ),
        ),
        @AttributeOverride(
            name = "line2",
            column = @Column( name = "work_address_line2" )
        ),
        @AttributeOverride(
            name = "zipCode.postalCode",
            column = @Column( name = "work_address_postal_cd" )
        ),
        @AttributeOverride(
            name = "zipCode.plus4",
            column = @Column( name = "work_address_postal_plus4" )
        )
    )
    private Address workAddress;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This way, the mapping conflict is resolved by setting up explicit name-based property-column type mappings.</p>
</div>
</div>
<div class="sect3">
<h4 id="embeddable-multiple-namingstrategy">ImplicitNamingStrategy</h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>This is a Hibernate specific feature.
Users concerned with JPA provider portability should instead prefer explicit column naming with <a href="#embeddable-multiple-jpa"><code>@AttributeOverride</code></a>.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Hibernate naming strategies are covered in detail in <a href="chapters/domain/naming.html#naming">Naming</a>.
However, for the purposes of this discussion, Hibernate has the capability to interpret implicit column names in a way that is safe for use with multiple embeddable types.</p>
</div>
<div class="exampleblock">
<div class="title">Example 99. Enabling embeddable type safe implicit naming</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">MetadataSources sources = ...;
sources.addAnnotatedClass( Address.class );
sources.addAnnotatedClass( Name.class );
sources.addAnnotatedClass( Contact.class );

Metadata metadata = sources.getMetadataBuilder().applyImplicitNamingStrategy( ImplicitNamingStrategyComponentPathImpl.INSTANCE )
...
.build();</code></pre>
</div>
</div>
</div>
</div>
<div class="exampleblock">
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">create table Contact(
    id integer not null,
    name_firstName VARCHAR,
    name_middleName VARCHAR,
    name_lastName VARCHAR,
    homeAddress_line1 VARCHAR,
    homeAddress_line2 VARCHAR,
    homeAddress_zipCode_postalCode VARCHAR,
    homeAddress_zipCode_plus4 VARCHAR,
    mailingAddress_line1 VARCHAR,
    mailingAddress_line2 VARCHAR,
    mailingAddress_zipCode_postalCode VARCHAR,
    mailingAddress_zipCode_plus4 VARCHAR,
    workAddress_line1 VARCHAR,
    workAddress_line2 VARCHAR,
    workAddress_zipCode_postalCode VARCHAR,
    workAddress_zipCode_plus4 VARCHAR,
    ...
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Now the "path" to attributes are used in the implicit column naming.
You could even develop your own to do special implicit naming.</p>
</div>
</div>
<div class="sect3">
<h4 id="embeddable-collections">Collections of embeddable types</h4>
<div class="paragraph">
<p>Collections of embeddable types are specifically value collections (as embeddable types are a value type).
Value collections are covered in detail in <a href="chapters/domain/collections.html#collections-value">Collections of value types</a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="embeddable-mapkey">Embeddable types as Map key</h4>
<div class="paragraph">
<p>Embeddable types can also be used as <code>Map</code> keys.
This topic is converted in detail in <a href="chapters/domain/collections.html#collections-map">Map - key</a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="embeddable-identifier">Embeddable types as identifiers</h4>
<div class="paragraph">
<p>Embeddable types can also be used as entity type identifiers.
This usage is covered in detail in <a href="chapters/domain/identifiers.html#identifiers-composite">Composite identifiers</a>.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Embeddable types that are used as collection entries, map keys or entity type identifiers cannot include their own collection mappings.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="entity">Entity types</h3>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="title">Usage of the word <em>entity</em></div>
<div class="paragraph">
<p>The entity type describes the mapping between the actual persistable domain model object and a database table row.
To avoid any confusion with the annotation that marks a given entity type, the annotation will be further referred as <code>@Entity</code>.</p>
</div>
<div class="paragraph">
<p>Throughout this chapter and thereafter, entity types will be simply referred as <em>entity</em>.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="entity-pojo">POJO Models</h4>
<div class="paragraph">
<p>Section <em>2.1 The Entity Class</em> of the <em>JPA 2.1 specification</em> defines its requirements for an entity class.
Applications that wish to remain portable across JPA providers should adhere to these requirements.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The entity class must be annotated with the <code>javax.persistence.Entity</code> annotation (or be denoted as such in XML mapping)</p>
</li>
<li>
<p>The entity class must have a public or protected no-argument constructor. It may define additional constructors as well.</p>
</li>
<li>
<p>The entity class must be a top-level class.</p>
</li>
<li>
<p>An enum or interface may not be designated as an entity.</p>
</li>
<li>
<p>The entity class must not be final. No methods or persistent instance variables of the entity class may be final.</p>
</li>
<li>
<p>If an entity instance is to be used remotely as a detached object, the entity class must implement the <code>Serializable</code> interface.</p>
</li>
<li>
<p>Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.</p>
</li>
<li>
<p>The persistent state of an entity is represented by instance variables, which may correspond to JavaBean-style properties.
An instance variable must be directly accessed only from within the methods of the entity by the entity instance itself.
The state of the entity is available to clients only through the entity’s accessor methods (getter/setter methods) or other business methods.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Hibernate, however, is not as strict in its requirements. The differences from the list above include:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The entity class must have a no-argument constructor, which may be public, protected or package visibility. It may define additional constructors as well.</p>
</li>
<li>
<p>The entity class <em>need not</em> be a top-level class.</p>
</li>
<li>
<p>Technically Hibernate can persist final classes or classes with final persistent state accessor (getter/setter) methods.
However, it is generally not a good idea as doing so will stop Hibernate from being able to generate proxies for lazy-loading the entity.</p>
</li>
<li>
<p>Hibernate does not restrict the application developer from exposing instance variables and reference them from outside the entity class itself.
The validity of such a paradigm, however, is debatable at best.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Let&#8217;s look at each requirement in detail.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-final">Prefer non-final classes</h4>
<div class="paragraph">
<p>A central feature of Hibernate is the ability to load lazily certain entity instance variables (attributes) via runtime proxies.
This feature depends upon the entity class being non-final or else implementing an interface that declares all the attribute getters/setters.
You can still persist final classes that do not implement such an interface with Hibernate,
but you will not be able to use proxies for fetching lazy associations, therefore limiting your options for performance tuning.
For the very same reason, you should also avoid declaring persistent attribute getters and setters as final.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Starting in 5.0 Hibernate offers a more robust version of bytecode enhancement as another means for handling lazy loading.
Hibernate had some bytecode re-writing capabilities prior to 5.0 but they were very rudimentary.
See the <a href="chapters/pc/BytecodeEnhancement.html#BytecodeEnhancement">BytecodeEnhancement</a> for additional information on fetching and on bytecode enhancement.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-constructor">Implement a no-argument constructor</h4>
<div class="paragraph">
<p>The entity class should have a no-argument constructor. Both Hibernate and JPA require this.</p>
</div>
<div class="paragraph">
<p>JPA requires that this constructor be defined as public or protected.
Hibernate, for the most part, does not care about the constructor visibility, as long as the system SecurityManager allows overriding the visibility setting.
That said, the constructor should be defined with at least package visibility if you wish to leverage runtime proxy generation.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-accessors">Declare getters and setters for persistent attributes</h4>
<div class="paragraph">
<p>The JPA specification requires this, otherwise the model would prevent accessing the entity persistent state fields directly from outside the entity itself.</p>
</div>
<div class="paragraph">
<p>Although Hibernate does not require it, it is recommended to follow the JavaBean conventions and define getters and setters for entity persistent attributes.
Nevertheless, you can still tell Hibernate to directly access the entity fields.</p>
</div>
<div class="paragraph">
<p>Attributes (whether fields or getters/setters) need not be declared public.
Hibernate can deal with attributes declared with public, protected, package or private visibility.
Again, if wanting to use runtime proxy generation for lazy loading, the getter/setter should grant access to at least package visibility.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-identifier">Provide identifier attribute(s)</h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Historically this was considered optional.
However, not defining identifier attribute(s) on the entity should be considered a deprecated feature that will be removed in an upcoming release.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The identifier attribute does not necessarily need to be mapped to the column(s) that physically define the primary key.
However, it should map to column(s) that can uniquely identify each row.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>We recommend that you declare consistently-named identifier attributes on persistent classes and that you use a nullable (i.e., non-primitive) type.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The placement of the <code>@Id</code> annotation marks the <a href="chapters/domain/access.html#access">persistence state access strategy</a>.</p>
</div>
<div class="exampleblock">
<div class="title">Example 100. Identifier</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Id
private Integer id;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Hibernate offers multiple identifier generation strategies, see the <a href="chapters/domain/identifiers.html#identifiers">Identifier Generators</a> chapter for more about this topic.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-mapping">Mapping the entity</h4>
<div class="paragraph">
<p>The main piece in mapping the entity is the <code>javax.persistence.Entity</code> annotation.
The <code>@Entity</code> annotation defines just one attribute <code>name</code> which is used to give a specific entity name for use in JPQL queries.
By default, the entity name represents the unqualified name of the entity class itself.</p>
</div>
<div class="exampleblock">
<div class="title">Example 101. Simple <code>@Entity</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Simple {
    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>An entity models a database table.
The identifier uniquely identifies each row in that table.
By default, the name of the table is assumed to be the same as the name of the entity.
To explicitly give the name of the table or to specify other information about the table, we would use the <code>javax.persistence.Table</code> annotation.</p>
</div>
<div class="exampleblock">
<div class="title">Example 102. Simple <code>@Entity</code> with <code>@Table</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
@Table( catalog = "CRM", schema = "purchasing", name = "t_simple" )
public class Simple {
    ...
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-model-pojo-equalshashcode">Implementing <code>equals()</code> and <code>hashCode()</code></h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Much of the discussion in this section deals with the relation of an entity to a Hibernate Session, whether the entity is managed, transient or detached.
If you are unfamiliar with these topics, they are explained in the <a href="chapters/pc/PersistenceContext.html#pc">Persistence Context</a> chapter.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Whether to implement <code>equals()</code> and <code>hashCode()</code> methods in your domain model, let alone how to implement them, is a surprisingly tricky discussion when it comes to ORM.</p>
</div>
<div class="paragraph">
<p>There is really just one absolute case: a class that acts as an identifier must implement equals/hashCode based on the id value(s).
Generally, this is pertinent for user-defined classes used as composite identifiers.
Beyond this one very specific use case and few others we will discuss below, you may want to consider not implementing equals/hashCode altogether.</p>
</div>
<div class="paragraph">
<p>So what&#8217;s all the fuss? Normally, most Java objects provide a built-in <code>equals()</code> and <code>hashCode()</code> based on the object&#8217;s identity, so each new object will be different from all others.
This is generally what you want in ordinary Java programming.
Conceptually however this starts to break down when you start to think about the possibility of multiple instances of a class representing the same data.</p>
</div>
<div class="paragraph">
<p>This is, in fact, exactly the case when dealing with data coming from a database.
Every time we load a specific <code>Person</code> from the database we would naturally get a unique instance.
Hibernate, however, works hard to make sure that does not happen within a given <code>Session</code>.
In fact, Hibernate guarantees equivalence of persistent identity (database row) and Java identity inside a particular session scope.
So if we ask a Hibernate <code>Session</code> to load that specific Person multiple times we will actually get back the same <em>instance</em>:</p>
</div>
<div class="exampleblock">
<div class="title">Example 103. Scope of identity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;

Person p1 = session.get( Person.class,1 );
Person p2 = session.get( Person.class,1 );

// this evaluates to true
assert p1==p2;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Consider another example using a persistent <code>java.util.Set</code>:</p>
</div>
<div class="exampleblock">
<div class="title">Example 104. Set usage with Session-scoped identity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;

Club club = session.get( Club.class,1 );

Person p1 = session.get( Person.class,1 );
Person p2 = session.get( Person.class,1 );

club.getMembers().add( p1 );
club.getMembers().add( p2 );

// this evaluates to true
assert club.getMembers.size()==1;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>However, the semantic changes when we mix instances loaded from different Sessions:</p>
</div>
<div class="exampleblock">
<div class="title">Example 105. Mixed Sessions</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session1=...;
Session session2=...;

Person p1 = session1.get( Person.class,1 );
Person p2 = session2.get( Person.class,1 );

// this evaluates to false
assert p1==p2;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session1=...;
Session session2=...;

Club club = session1.get( Club.class,1 );

Person p1 = session1.get( Person.class,1 );
Person p2 = session2.get( Person.class,1 );

club.getMembers().add( p1 );
club.getMembers().add( p2 );

// this evaluates to ... well it depends
assert club.getMembers.size()==1;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Specifically the outcome in this last example will depend on whether the <code>Person</code> class implemented equals/hashCode, and, if so, how.</p>
</div>
<div class="paragraph">
<p>Consider yet another case:</p>
</div>
<div class="exampleblock">
<div class="title">Example 106. Sets with transient entities</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;

Club club = session.get( Club.class,1 );

Person p1 = new Person(...);
Person p2 = new Person(...);

club.getMembers().add( p1 );
club.getMembers().add( p2 );

// this evaluates to ... again, it depends
assert club.getMembers.size()==1;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In cases where you will be dealing with entities outside of a Session (whether they be transient or detached), especially in cases where you will be using them in Java collections,
you should consider implementing equals/hashCode.</p>
</div>
<div class="paragraph">
<p>A common initial approach is to use the entity&#8217;s identifier attribute as the basis for equals/hashCode calculations:</p>
</div>
<div class="exampleblock">
<div class="title">Example 107. Naive equals/hashCode implementation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Person {

    @Id
    @GeneratedValue
    private Integer id;

    @Override
    public int hashCode() {
        return Objects.hash( id );
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( !( o instanceof Person ) ) {
            return false;
        }
        Person person = (Person) o;
        return Objects.equals( id, person.id );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>It turns out that this still breaks when adding transient instance of <code>Person</code> to a set as we saw in the last example:</p>
</div>
<div class="exampleblock">
<div class="title">Example 108. Still trouble</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;
session.getTransaction().begin();

Club club = session.get( Club.class,1 );

Person p1 = new Person(...);
Person p2 = new Person(...);

club.getMembers().add( p1 );
club.getMembers().add( p2 );

session.getTransaction().commit();

// will actually resolve to false!
assert club.getMembers().contains( p1 );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The issue here is a conflict between the use of generated identifier, the contract of <code>Set</code> and the equals/hashCode implementations.
<code>Set</code> says that the equals/hashCode value for an object should not change while the object is part of the <code>Set</code>.
But that is exactly what happened here because the equals/hasCode are based on the (generated) id, which was not set until the <code>session.getTransaction().commit()</code> call.</p>
</div>
<div class="paragraph">
<p>Note that this is just a concern when using generated identifiers.
If you are using assigned identifiers this will not be a problem, assuming the identifier value is assigned prior to adding to the <code>Set</code>.</p>
</div>
<div class="paragraph">
<p>Another option is to force the identifier to be generated and set prior to adding to the <code>Set</code>:</p>
</div>
<div class="exampleblock">
<div class="title">Example 109. Forcing identifier generation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;
session.getTransaction().begin();

Club club = session.get( Club.class,1 );

Person p1 = new Person(...);
Person p2 = new Person(...);

session.save( p1 );
session.save( p2 );
session.flush();

club.getMembers().add( p1 );
club.getMembers().add( p2 );

session.getTransaction().commit();

// will actually resolve to false!
assert club.getMembers().contains( p1 );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>But this is often not feasible.</p>
</div>
<div class="paragraph">
<p>The final approach is to use a "better" equals/hashCode implementation, making use of a natural-id or business-key.</p>
</div>
<div class="exampleblock">
<div class="title">Example 110. Better equals/hashCode with natural-id</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Person {

    @Id
    @GeneratedValue
    private Integer id;

    @NaturalId
    private String ssn;

    protected Person() {
        // Constructor for ORM
    }

    public Person( String ssn ) {
        // Constructor for app
        this.ssn = ssn;
    }

    @Override
    public int hashCode() {
        return Objects.hash( ssn );
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( !( o instanceof Person ) ) {
            return false;
        }
        Person person = (Person) o;
        return Objects.equals( ssn, person.ssn );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see the question of equals/hashCode is not trivial, nor is there a one-size-fits-all solution.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Although using a natural-id is best for <code>equals</code> and <code>hashCode</code>, sometimes you only have the entity identifier that provides a unique constraint.</p>
</div>
<div class="paragraph">
<p>It&#8217;s possible to use the entity identifier for equality check, but it needs a workaround:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>you need to provide a constant value for <code>hashCode</code> so that the hash code value does not change before and after the entity is flushed.</p>
</li>
<li>
<p>you need to compare the entity identifier equality only for non-transient entities.</p>
</li>
</ul>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For details on mapping the identifier, see the <a href="chapters/domain/identifiers.html#identifiers">Identifiers</a> chapter.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-optlock">Mapping optimistic locking</h4>
<div class="paragraph">
<p>JPA defines support for optimistic locking based on either a version (sequential numeric) or timestamp strategy.
To enable this style of optimistic locking simply add the <code>javax.persistence.Version</code> to the persistent attribute that defines the optimistic locking value.
According to JPA, the valid types for these attributes are limited to:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>int</code> or <code>Integer</code></p>
</li>
<li>
<p><code>short</code> or <code>Short</code></p>
</li>
<li>
<p><code>long</code> or <code>Long</code></p>
</li>
<li>
<p><code>java.sql.Timestamp</code></p>
</li>
</ul>
</div>
<div id="entity-pojo-optlock-version-example" class="exampleblock">
<div class="title">Example 111. <code>@Version</code> annotation mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Course {

    @Id
    private Integer id;

    @Version
    private Integer version;
    ...
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Thing {

    @Id
    private Integer id;

    @Version
    private Timestamp ts;

    ...
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Thing2 {

    @Id
    private Integer id;

    @Version
    private Instant ts;
    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="entity-pojo-optlock-versionless">Versionless optimistic locking</h5>
<div class="paragraph">
<p>Although the default <code>@Version</code> property optimistic locking mechanism is sufficient in many situations,
sometimes, you need rely on the actual database row column values to prevent <strong>lost updates</strong>.</p>
</div>
<div class="paragraph">
<p>Hibernate supports a form of optimistic locking that does not require a dedicated "version attribute".
This is also useful for use with modeling legacy schemas.</p>
</div>
<div class="paragraph">
<p>The idea is that you can get Hibernate to perform "version checks" using either all of the entity&#8217;s attributes, or just the attributes that have changed.
This is achieved through the use of the
<a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/OptimisticLocking.html"><code>@OptimisticLocking</code></a>
annotation which defines a single attribute of type
<a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/OptimisticLockType.html"><code>org.hibernate.annotations.OptimisticLockType</code></a>.</p>
</div>
<div class="paragraph">
<p>There are 4 available OptimisticLockTypes:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>NONE</code></dt>
<dd>
<p>optimistic locking is disabled even if there is a <code>@Version</code> annotation present</p>
</dd>
<dt class="hdlist1"><code>VERSION</code> (the default)</dt>
<dd>
<p>performs optimistic locking based on a <code>@Version</code> as described above</p>
</dd>
<dt class="hdlist1"><code>ALL</code></dt>
<dd>
<p>performs optimistic locking based on <em>all</em> fields as part of an expanded WHERE clause restriction for the UPDATE/DELETE SQL statements</p>
</dd>
<dt class="hdlist1"><code>DIRTY</code></dt>
<dd>
<p>performs optimistic locking based on <em>dirty</em> fields as part of an expanded WHERE clause restriction for the UPDATE/DELETE SQL statements</p>
</dd>
</dl>
</div>
<div class="sect5">
<h6 id="entity-pojo-optlock-versionless-all">Versionless optimistic locking using <code>OptimisticLockType.ALL</code></h6>
<div id="locking-optimistic-lock-type-all-example" class="exampleblock">
<div class="title">Example 112. <code>OptimisticLockType.ALL</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
@OptimisticLocking(type = OptimisticLockType.ALL)
@DynamicUpdate
public static class Person {

    @Id
    private Long id;

    @Column(name = "`name`")
    private String name;

    private String country;

    private String city;

    @Column(name = "created_on")
    private Timestamp createdOn;

    //Getters and setters are omitted for brevity
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When you need to modify the <code>Person</code> entity above:</p>
</div>
<div id="locking-optimistic-lock-type-all-update-example" class="exampleblock">
<div class="title">Example 113. <code>OptimisticLockType.ALL</code> update example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = entityManager.find( Person.class, 1L );
person.setCity( "Washington D.C." );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">UPDATE
    Person
SET
    city=?
WHERE
    id=?
    AND city=?
    AND country=?
    AND created_on=?
    AND "name"=?

-- binding parameter [1] as [VARCHAR] - [Washington D.C.]
-- binding parameter [2] as [BIGINT] - [1]
-- binding parameter [3] as [VARCHAR] - [New York]
-- binding parameter [4] as [VARCHAR] - [US]
-- binding parameter [5] as [TIMESTAMP] - [2016-11-16 16:05:12.876]
-- binding parameter [6] as [VARCHAR] - [John Doe]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see, all the columns of the associated database row are used in the <code>WHERE</code> clause.
If any column has changed after the row was loaded, there won&#8217;t be any match, and a <code>StaleStateException</code> or an <code>OptimisticLockException</code>
is going to be thrown.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>When using <code>OptimisticLockType.ALL</code>, you should also use <code>@DynamicUpdate</code> because the <code>UPDATE</code> statement must take into consideration all the entity property values.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect5">
<h6 id="entity-pojo-optlock-versionless-dirty">Versionless optimistic locking using <code>OptimisticLockType.DIRTY</code></h6>
<div class="paragraph">
<p>The <code>OptimisticLockType.DIRTY</code> differs from <code>OptimisticLockType.ALL</code>
in that it only takes into consideration the entity properties that have changed
since the entity was loaded in the currently running Persistence Context.</p>
</div>
<div id="locking-optimistic-lock-type-dirty-example" class="exampleblock">
<div class="title">Example 114. <code>OptimisticLockType.DIRTY</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
@OptimisticLocking(type = OptimisticLockType.DIRTY)
@DynamicUpdate
@SelectBeforeUpdate
public static class Person {

    @Id
    private Long id;

    @Column(name = "`name`")
    private String name;

    private String country;

    private String city;

    @Column(name = "created_on")
    private Timestamp createdOn;

    //Getters and setters are omitted for brevity
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When you need to modify the <code>Person</code> entity above:</p>
</div>
<div id="locking-optimistic-lock-type-dirty-update-example" class="exampleblock">
<div class="title">Example 115. <code>OptimisticLockType.DIRTY</code> update example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = entityManager.find( Person.class, 1L );
person.setCity( "Washington D.C." );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">UPDATE
    Person
SET
    city=?
WHERE
    id=?
    and city=?

-- binding parameter [1] as [VARCHAR] - [Washington D.C.]
-- binding parameter [2] as [BIGINT] - [1]
-- binding parameter [3] as [VARCHAR] - [New York]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This time, only the database column that has changed was used in the <code>WHERE</code> clause.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The main advantage of <code>OptimisticLockType.DIRTY</code> over <code>OptimisticLockType.ALL</code>
and the default <code>OptimisticLockType.VERSION</code> used implicitly along with the <code>@Version</code> mapping,
is that it allows you to minimize the risk of <code>OptimisticLockException</code> across non-overlapping entity property changes.</p>
</div>
<div class="paragraph">
<p>When using <code>OptimisticLockType.DIRTY</code>, you should also use <code>@DynamicUpdate</code> because the <code>UPDATE</code> statement must take into consideration all the dirty entity property values,
and also the <code>@SelectBeforeUpdate</code> annotation so that detached entities are properly handled by the
<a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/Session.html#update-java.lang.Object-"><code>Session#update(entity)</code></a> operation.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="access">Access strategies</h4>
<div class="paragraph">
<p>As a JPA provider, Hibernate can introspect both the entity attributes (instance fields) or the accessors (instance properties).
By default, the placement of the <code>@Id</code> annotation gives the default access strategy.
When placed on a field, Hibernate will assume field-based access.
Place on the identifier getter, Hibernate will use property-based access.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>You should pay attention to <a href="https://docs.oracle.com/javase/7/docs/api/java/beans/Introspector.html#decapitalize(java.lang.String)">Java Beans specification</a> in regard to naming properties to avoid
issues such as <a href="https://hibernate.atlassian.net/browse/HCANN-63">Property name beginning with at least two uppercase characters has odd functionality in HQL</a>!</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Embeddable types inherit the access strategy from their parent entities.</p>
</div>
<div class="sect4">
<h5 id="field-based-access">Field-based access</h5>
<div class="exampleblock">
<div class="title">Example 116. Field-based access</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Simple {

    @Id
    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId( Integer id ) {
        this.id = id;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When using field-based access, adding other entity-level methods is much more flexible because Hibernate won&#8217;t consider those part of the persistence state.
To exclude a field from being part of the entity persistent state, the field must be marked with the <code>@Transient</code> annotation.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Another advantage of using field-based access is that some entity attributes can be hidden from outside the entity.
An example of such attribute is the entity <code>@Version</code> field, which must not be manipulated by the data access layer.
With field-based access, we can simply omit the getter and the setter for this version field, and Hibernate can still leverage the optimistic concurrency control mechanism.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect4">
<h5 id="property-based-access">Property-based access</h5>
<div class="exampleblock">
<div class="title">Example 117. Property-based access</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Simple {

    private Integer id;

    @Id
    public Integer getId() {
        return id;
    }

    public void setId( Integer id ) {
        this.id = id;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When using property-based access, Hibernate uses the accessors for both reading and writing the entity state.
Every other method that will be added to the entity (e.g. helper methods for synchronizing both ends of a bidirectional one-to-many association) will have to be marked with the <code>@Transient</code> annotation.</p>
</div>
</div>
<div class="sect4">
<h5 id="_overriding_the_default_access_strategy">Overriding the default access strategy</h5>
<div class="paragraph">
<p>The default access strategy mechanism can be overridden with the JPA <code>@Access</code> annotation.
In the following example, the <code>@Version</code> attribute is accessed by its field and not by its getter, like the rest of entity attributes.</p>
</div>
<div class="exampleblock">
<div class="title">Example 118. Overriding access strategy</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Simple {

    private Integer id;

    @Version
    @Access( AccessType.FIELD )
    private Integer version;

    @Id
    public Integer getId() {
        return id;
    }

    public void setId( Integer id ) {
        this.id = id;
    }
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="access-embeddable-types">Embeddable types and access strategy</h5>
<div class="paragraph">
<p>Because embeddables are managed by their owning entities, the access strategy is therefore inherited from the entity too.
This applies to both simple embeddable types as well as for collection of embeddables.</p>
</div>
<div class="paragraph">
<p>The embeddable types can overrule the default implicit access strategy (inherited from the owning entity).
In the following example, the embeddable uses property-based access, no matter what access strategy the owning entity is choosing:</p>
</div>
<div class="exampleblock">
<div class="title">Example 119. Embeddable with exclusive access strategy</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Embeddable
@Access(AccessType.PROPERTY)
public static class Change {

    private String path;

    private String diff;

    public Change() {}

    @Column(name = "path", nullable = false)
    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Column(name = "diff", nullable = false)
    public String getDiff() {
        return diff;
    }

    public void setDiff(String diff) {
        this.diff = diff;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The owning entity can use field-based access, while the embeddable uses property-based access as it has chosen explicitly:</p>
</div>
<div class="exampleblock">
<div class="title">Example 120. Entity including a single embeddable type</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Patch {

    @Id
    private Long id;

    @Embedded
    private Change change;
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This works also for collection of embeddable types:</p>
</div>
<div class="exampleblock">
<div class="title">Example 121. Entity including a collection of embeddable types</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Patch {

    @Id
    private Long id;

    @ElementCollection
    @CollectionTable(
        name="patch_change",
        joinColumns=@JoinColumn(name="patch_id")
    )
    @OrderColumn(name = "index_id")
    private List&lt;Change&gt; changes = new ArrayList&lt;&gt;();

    public List&lt;Change&gt; getChanges() {
        return changes;
    }
}</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="identifiers">Identifiers</h3>
<div class="paragraph">
<p>Identifiers model the primary key of an entity. They are used to uniquely identify each specific entity.</p>
</div>
<div class="paragraph">
<p>Hibernate and JPA both make the following assumptions about the corresponding database column(s):</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>UNIQUE</code></dt>
<dd>
<p>The values must uniquely identify each row.</p>
</dd>
<dt class="hdlist1"><code>NOT NULL</code></dt>
<dd>
<p>The values cannot be null. For composite ids, no part can
be null.</p>
</dd>
<dt class="hdlist1"><code>IMMUTABLE</code></dt>
<dd>
<p>The values, once inserted, can never be changed.
This is more a general guide, than a hard-fast rule as opinions vary.
JPA defines the behavior of changing the value of the identifier attribute to be undefined; Hibernate simply does not support that.
In cases where the values for the PK you have chosen will be updated, Hibernate recommends mapping the mutable value as a natural id, and use a surrogate id for the PK.
See <a href="chapters/domain/natural_id.html#naturalid">Natural Ids</a>.</p>
</dd>
</dl>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Technically the identifier does not have to map to the column(s) physically defined as the table primary key.
They just need to map to column(s) that uniquely identify each row.
However this documentation will continue to use the terms identifier and primary key interchangeably.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Every entity must define an identifier. For entity inheritance hierarchies, the identifier must be defined just on the entity that is the root of the hierarchy.</p>
</div>
<div class="paragraph">
<p>An identifier might be simple (single value) or composite (multiple values).</p>
</div>
<div class="sect3">
<h4 id="identifiers-simple">Simple identifiers</h4>
<div class="paragraph">
<p>Simple identifiers map to a single basic attribute, and are denoted using the <code>javax.persistence.Id</code> annotation.</p>
</div>
<div class="paragraph">
<p>According to JPA only the following types should be used as identifier attribute types:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>any Java primitive type</p>
</li>
<li>
<p>any primitive wrapper type</p>
</li>
<li>
<p><code>java.lang.String</code></p>
</li>
<li>
<p><code>java.util.Date</code> (TemporalType#DATE)</p>
</li>
<li>
<p><code>java.sql.Date</code></p>
</li>
<li>
<p><code>java.math.BigDecimal</code></p>
</li>
<li>
<p><code>java.math.BigInteger</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Any types used for identifier attributes beyond this list will not be portable.</p>
</div>
<div class="sect4">
<h5 id="identifiers-simple-assigned">Assigned identifiers</h5>
<div class="paragraph">
<p>Values for simple identifiers can be assigned, as we have seen in the examples above.
The expectation for assigned identifier values is that the application assigns (sets them on the entity attribute) prior to calling save/persist.</p>
</div>
<div class="exampleblock">
<div class="title">Example 122. Simple assigned identifier</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class MyEntity {

    @Id
    public Integer id;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="identifiers-simple-generated">Generated identifiers</h5>
<div class="paragraph">
<p>Values for simple identifiers can be generated. To denote that an identifier attribute is generated, it is annotated with <code>javax.persistence.GeneratedValue</code></p>
</div>
<div class="exampleblock">
<div class="title">Example 123. Simple generated identifier</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class MyEntity {

    @Id
    @GeneratedValue
    public Integer id;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Additionally, to the type restriction list above, JPA says that if using generated identifier values (see below) only integer types (short, int, long) will be portably supported.</p>
</div>
<div class="paragraph">
<p>The expectation for generated identifier values is that Hibernate will generate the value when the save/persist occurs.</p>
</div>
<div class="paragraph">
<p>Identifier value generations strategies are discussed in detail in the <a href="#identifiers-generators">Generated identifier values</a> section.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-composite">Composite identifiers</h4>
<div class="paragraph">
<p>Composite identifiers correspond to one or more persistent attributes.
Here are the rules governing composite identifiers, as defined by the JPA specification.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The composite identifier must be represented by a "primary key class".
The primary key class may be defined using the <code>javax.persistence.EmbeddedId</code> annotation (see <a href="#identifiers-composite-aggregated">Composite identifiers with <code>@EmbeddedId</code></a>),
or defined using the <code>javax.persistence.IdClass</code> annotation (see <a href="#identifiers-composite-nonaggregated">Composite identifiers with <code>@IdClass</code></a>).</p>
</li>
<li>
<p>The primary key class must be public and must have a public no-arg constructor.</p>
</li>
<li>
<p>The primary key class must be serializable.</p>
</li>
<li>
<p>The primary key class must define equals and hashCode methods, consistent with equality for the underlying database types to which the primary key is mapped.</p>
</li>
</ul>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The restriction that a composite identifier has to be represented by a "primary key class" is only JPA specific.
Hibernate does allow composite identifiers to be defined without a "primary key class", although that modeling technique is deprecated and therefore omitted from this discussion.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The attributes making up the composition can be either basic, composite, ManyToOne.
Note especially that collections and one-to-ones are never appropriate.</p>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-composite-aggregated">Composite identifiers with <code>@EmbeddedId</code></h4>
<div class="paragraph">
<p>Modeling a composite identifier using an EmbeddedId simply means defining an embeddable to be a composition for the one or more attributes making up the identifier,
and then exposing an attribute of that embeddable type on the entity.</p>
</div>
<div class="exampleblock">
<div class="title">Example 124. Basic EmbeddedId</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Login {

    @EmbeddedId
    private PK pk;

    @Embeddable
    public static class PK implements Serializable {

        private String system;

        private String username;

        ...
    }

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As mentioned before, EmbeddedIds can even contain ManyToOne attributes.</p>
</div>
<div class="exampleblock">
<div class="title">Example 125. EmbeddedId with ManyToOne</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Login {

    @EmbeddedId
    private PK pk;

    @Embeddable
    public static class PK implements Serializable {

        @ManyToOne
        private System system;

        private String username;

        ...
    }

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Hibernate supports directly modeling the ManyToOne in the PK class, whether EmbeddedId or IdClass.
However that is not portably supported by the JPA specification.
In JPA terms one would use "derived identifiers"; for details, see <a href="#identifiers-derived">Derived Identifiers</a>.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-composite-nonaggregated">Composite identifiers with <code>@IdClass</code></h4>
<div class="paragraph">
<p>Modeling a composite identifier using an IdClass differs from using an EmbeddedId in that the entity defines each individual attribute making up the composition.
The IdClass simply acts as a "shadow".</p>
</div>
<div class="exampleblock">
<div class="title">Example 126. Basic IdClass</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
@IdClass( PK.class )
public class Login {

    @Id
    private String system;

    @Id
    private String username;

    public static class PK implements Serializable {

        private String system;

        private String username;

        ...
    }

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Non-aggregated composite identifiers can also contain ManyToOne attributes as we saw with aggregated ones (still non-portably).</p>
</div>
<div class="exampleblock">
<div class="title">Example 127. IdClass with ManyToOne</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
@IdClass( PK.class )
public class Login {

    @Id
    @ManyToOne
    private System system;

    @Id
    private String username;

    public static class PK implements Serializable {

        private System system;

        private String username;

        ...
    }

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>With non-aggregated composite identifiers, Hibernate also supports "partial" generation of the composite values.</p>
</div>
<div class="exampleblock">
<div class="title">Example 128. IdClass with partial generation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
@IdClass( PK.class )
public class LogFile {

    @Id
    private String name;

    @Id
    private LocalDate date;

    @Id
    @GeneratedValue
    private Integer uniqueStamp;

    public static class PK implements Serializable {

        private String name;

        private LocalDate date;

        private Integer uniqueStamp;

        ...
    }

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>This feature exists because of a highly questionable interpretation of the JPA specification made by the SpecJ committee.
Hibernate does not feel that JPA defines support for this, but added the feature simply to be usable in SpecJ benchmarks.
Use of this feature may or may not be portable from a JPA perspective.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-composite-associations">Composite identifiers with associations</h4>
<div class="paragraph">
<p>Hibernate allows defining a composite identifier out of entity associations.
In the following example, the <code>PersonAddress</code> entity identifier is formed of two <code>@ManyToOne</code> associations.</p>
</div>
<div class="exampleblock">
<div class="title">Example 129. Composite identifiers with associations</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class PersonAddress  implements Serializable {

    @Id
    @ManyToOne
    private Person person;

    @Id
    @ManyToOne()
    private Address address;

    public PersonAddress() {}

    public PersonAddress(Person person, Address address) {
        this.person = person;
        this.address = address;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PersonAddress that = (PersonAddress) o;
        return Objects.equals(person, that.person) &amp;&amp;
                Objects.equals(address, that.address);
    }

    @Override
    public int hashCode() {
        return Objects.hash(person, address);
    }
}

@Entity
public class Person  {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String registrationNumber;

    public Person() {}

    public Person(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public Long getId() {
        return id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(registrationNumber, person.registrationNumber);
    }

    @Override
    public int hashCode() {
        return Objects.hash(registrationNumber);
    }
}

@Entity
public class Address  {

    @Id
    @GeneratedValue
    private Long id;

    private String street;

    private String number;

    private String postalCode;

    public Address() {}

    public Address(String street, String number, String postalCode) {
        this.street = street;
        this.number = number;
        this.postalCode = postalCode;
    }

    public Long getId() {
        return id;
    }

    public String getStreet() {
        return street;
    }

    public String getNumber() {
        return number;
    }

    public String getPostalCode() {
        return postalCode;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Address address = (Address) o;
        return Objects.equals(street, address.street) &amp;&amp;
                Objects.equals(number, address.number) &amp;&amp;
                Objects.equals(postalCode, address.postalCode);
    }

    @Override
    public int hashCode() {
        return Objects.hash(street, number, postalCode);
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Although the mapping is much simpler than using an <code>@EmbeddedId</code> or an <code>@IdClass</code>, there&#8217;s no separation between the entity instance and the actual identifier.
To query this entity, an instance of the entity itself must be supplied to the persistence context.</p>
</div>
<div class="exampleblock">
<div class="title">Example 130. Composite identifiers with associations query</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">PersonAddress personAddress = entityManager.find(
    PersonAddress.class,
    new PersonAddress( person, address )
);</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-generators">Generated identifier values</h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>For discussion of generated values for non-identifier attributes, see <a href="chapters/domain/basic_types.html#mapping-generated">Generated properties</a>.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Hibernate supports identifier value generation across a number of different types.
Remember that JPA portably defines identifier value generation just for integer types.</p>
</div>
<div class="paragraph">
<p>Identifier value generation is indicates using the <code>javax.persistence.GeneratedValue</code> annotation.
The most important piece of information here is the specified <code>javax.persistence.GenerationType</code> which indicates how values will be generated.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The discussions below assume that the application is using Hibernate&#8217;s "new generator mappings" as indicated by the <code>hibernate.id.new_generator_mappings</code> setting or
<code>MetadataBuilder.enableNewIdentifierGeneratorSupport</code> method during bootstrap.
Starting with Hibernate 5, this is set to true by default.
If applications set this to false the resolutions discussed here will be very different.
The rest of the discussion here assumes this setting is enabled (true).</p>
</div>
</td>
</tr>
</table>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>AUTO</code> (the default)</dt>
<dd>
<p>Indicates that the persistence provider (Hibernate) should choose an appropriate generation strategy. See <a href="#identifiers-generators-auto">Interpreting AUTO</a>.</p>
</dd>
<dt class="hdlist1"><code>IDENTITY</code></dt>
<dd>
<p>Indicates that database IDENTITY columns will be used for primary key value generation. See <a href="#identifiers-generators-identity">Using IDENTITY columns</a>.</p>
</dd>
<dt class="hdlist1"><code>SEQUENCE</code></dt>
<dd>
<p>Indicates that database sequence should be used for obtaining primary key values. See <a href="#identifiers-generators-sequence">Using sequences</a>.</p>
</dd>
<dt class="hdlist1"><code>TABLE</code></dt>
<dd>
<p>Indicates that a database table should be used for obtaining primary key values. See <a href="#identifiers-generators-table">Using identifier table</a>.</p>
</dd>
</dl>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-generators-auto">Interpreting AUTO</h4>
<div class="paragraph">
<p>How a persistence provider interprets the AUTO generation type is left up to the provider.</p>
</div>
<div class="paragraph">
<p>The default behavior is to look at the java type of the identifier attribute.</p>
</div>
<div class="paragraph">
<p>If the identifier type is UUID, Hibernate is going to use an <a href="#identifiers-generators-uuid">UUID identifier</a>.</p>
</div>
<div class="paragraph">
<p>If the identifier type is numerical (e.g. <code>Long</code>, <code>Integer</code>), then Hibernate is going to use the <code>IdGeneratorStrategyInterpreter</code> to resolve the identifier generator strategy.
The <code>IdGeneratorStrategyInterpreter</code> has two implementations:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>FallbackInterpreter</code></dt>
<dd>
<p>This is the default strategy since Hibernate 5.0. For older versions, this strategy is enabled through the <a href="appendices/Configurations.html#configurations-mapping"><code>hibernate.id.new_generator_mappings</code></a> configuration property .
When using this strategy, <code>AUTO</code> always resolves to <code>SequenceStyleGenerator</code>.
If the underlying database supports sequences, then a SEQUENCE generator is used. Otherwise, a TABLE generator is going to be used instead.</p>
</dd>
<dt class="hdlist1"><code>LegacyFallbackInterpreter</code></dt>
<dd>
<p>This is a legacy mechanism that was used by Hibernate prior to version 5.0 or when the <a href="appendices/Configurations.html#configurations-mapping"><code>hibernate.id.new_generator_mappings</code></a> configuration property is false.
The legacy strategy maps <code>AUTO</code> to the <code>native</code> generator strategy which uses the <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/dialect/Dialect.html#getNativeIdentifierGeneratorStrategy--">Dialect#getNativeIdentifierGeneratorStrategy</a> to resolve the actual identifier generator (e.g. <code>identity</code> or <code>sequence</code>).</p>
</dd>
</dl>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-generators-sequence">Using sequences</h4>
<div class="paragraph">
<p>For implementing database sequence-based identifier value generation Hibernate makes use of its <code>org.hibernate.id.enhanced.SequenceStyleGenerator</code> id generator.
It is important to note that SequenceStyleGenerator is capable of working against databases that do not support sequences by switching to a table as the underlying backing.
This gives Hibernate a huge degree of portability across databases while still maintaining consistent id generation behavior (versus say choosing between SEQUENCE and IDENTITY).
This backing storage is completely transparent to the user.</p>
</div>
<div class="paragraph">
<p>The preferred (and portable) way to configure this generator is using the JPA-defined <code>javax.persistence.SequenceGenerator</code> annotation.</p>
</div>
<div class="paragraph">
<p>The simplest form is to simply request sequence generation; Hibernate will use a single, implicitly-named sequence (<code>hibernate_sequence</code>) for all such unnamed definitions.</p>
</div>
<div class="exampleblock">
<div class="title">Example 131. Unnamed sequence</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class MyEntity {

    @Id
    @GeneratedValue( generation = SEQUENCE )
    public Integer id;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Or a specifically named sequence can be requested.</p>
</div>
<div class="exampleblock">
<div class="title">Example 132. Named sequence</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class MyEntity {

    @Id
    @GeneratedValue( generation = SEQUENCE, name = "my_sequence" )
    public Integer id;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Use <code>javax.persistence.SequenceGenerator</code> to specify additional
configuration.</p>
</div>
<div class="exampleblock">
<div class="title">Example 133. Configured sequence</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class MyEntity {

    @Id
    @GeneratedValue( generation = SEQUENCE, name = "my_sequence" )
    @SequenceGenerator( name = "my_sequence", schema = "globals", allocationSize = 30 )
    public Integer id;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-generators-identity">Using IDENTITY columns</h4>
<div class="paragraph">
<p>For implementing identifier value generation based on IDENTITY columns,
Hibernate makes use of its <code>org.hibernate.id.IdentityGenerator</code> id generator which expects the identifier to generated by INSERT into the table.
IdentityGenerator understands 3 different ways that the INSERT-generated value might be retrieved:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>If Hibernate believes the JDBC environment supports <code>java.sql.Statement#getGeneratedKeys</code>, then that approach will be used for extracting the IDENTITY generated keys.</p>
</li>
<li>
<p>Otherwise, if <code>Dialect#supportsInsertSelectIdentity</code> reports true, Hibernate will use the Dialect specific INSERT+SELECT statement syntax.</p>
</li>
<li>
<p>Otherwise, Hibernate will expect that the database supports some form of asking for the most recently inserted IDENTITY value via a separate SQL command as indicated by <code>Dialect#getIdentitySelectString</code>.</p>
</li>
</ul>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>It is important to realize that this imposes a runtime behavior where the entity row <strong>must</strong> be physically inserted prior to the identifier value being known.
This can mess up extended persistence contexts (conversations).
Because of the runtime imposition/inconsistency Hibernate suggest other forms of identifier value generation be used.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>There is yet another important runtime impact of choosing IDENTITY generation: Hibernate will not be able to JDBC batching for inserts of the entities that use IDENTITY generation.
The importance of this depends on the application specific use cases.
If the application is not usually creating many new instances of a given type of entity that uses IDENTITY generation, then this is not an important impact since batching would not have been helpful anyway.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-generators-table">Using identifier table</h4>
<div class="paragraph">
<p>Hibernate achieves table-based identifier generation based on its <code>org.hibernate.id.enhanced.TableGenerator</code> id generator which defines a table capable of holding multiple named value segments for any number of entities.</p>
</div>
<div class="exampleblock">
<div class="title">Example 134. Table generator table structure</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">create table hibernate_sequences(
    sequence_name VARCHAR NOT NULL,
    next_val INTEGER NOT NULL
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The basic idea is that a given table-generator table (<code>hibernate_sequences</code> for example) can hold multiple segments of identifier generation values.</p>
</div>
<div class="exampleblock">
<div class="title">Example 135. Unnamed table generator</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class MyEntity {

    @Id
    @GeneratedValue( generation = TABLE )
    public Integer id;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>If no table name is given Hibernate assumes an implicit name of <code>hibernate_sequences</code>.
Additionally, because no <code>javax.persistence.TableGenerator#pkColumnValue</code> is specified, Hibernate will use the default segment (<code>sequence_name='default'</code>) from the hibernate_sequences table.</p>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-generators-uuid">Using UUID generation</h4>
<div class="paragraph">
<p>As mentioned above, Hibernate supports UUID identifier value generation.
This is supported through its <code>org.hibernate.id.UUIDGenerator</code> id generator.</p>
</div>
<div class="paragraph">
<p><code>UUIDGenerator</code> supports pluggable strategies for exactly how the UUID is generated.
These strategies are defined by the <code>org.hibernate.id.UUIDGenerationStrategy</code> contract.
The default strategy is a version 4 (random) strategy according to IETF RFC 4122.
Hibernate does ship with an alternative strategy which is a RFC 4122 version 1 (time-based) strategy (using ip address rather than mac address).</p>
</div>
<div class="exampleblock">
<div class="title">Example 136. Implicitly using the random UUID strategy</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class MyEntity {

    @Id
    @GeneratedValue
    public UUID id;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>To specify an alternative generation strategy, we&#8217;d have to define some configuration via <code>@GenericGenerator</code>.
Here we choose the RFC 4122 version 1 compliant strategy named <code>org.hibernate.id.uuid.CustomVersionOneStrategy</code>.</p>
</div>
<div class="exampleblock">
<div class="title">Example 137. Implicitly using the random UUID strategy</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class MyEntity {

    @Id
    @GeneratedValue( generator = "uuid" )
    @GenericGenerator(
        name = "uuid",
        strategy = "org.hibernate.id.UUIDGenerator",
        parameters = {
            @Parameter(
                name = "uuid_gen_strategy_class",
                value = "org.hibernate.id.uuid.CustomVersionOneStrategy"
            )
        }
    )
    public UUID id;

    ...

}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-generators-optimizer">Optimizers</h4>
<div class="paragraph">
<p>Most of the Hibernate generators that separately obtain identifier values from database structures support the use of pluggable optimizers.
Optimizers help manage the number of times Hibernate has to talk to the database in order to generate identifier values.
For example, with no optimizer applied to a sequence-generator, every time the application asked Hibernate to generate an identifier it would need to grab the next sequence value from the database.
But if we can minimize the number of times we need to communicate with the database here, the application will be able to perform better.
Which is, in fact, the role of these optimizers.</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">none</dt>
<dd>
<p>No optimization is performed. We communicate with the database each and every time an identifier value is needed from the generator.</p>
</dd>
<dt class="hdlist1">pooled-lo</dt>
<dd>
<p>The pooled-lo optimizer works on the principle that the increment-value is encoded into the database table/sequence structure.
In sequence-terms this means that the sequence is defined with a greater-that-1 increment size.</p>
<div class="paragraph">
<p>For example, consider a brand new sequence defined as <code>create sequence m_sequence start with 1 increment by 20</code>.
This sequence essentially defines a "pool" of 20 usable id values each and every time we ask it for its next-value.
The pooled-lo optimizer interprets the next-value as the low end of that pool.</p>
</div>
<div class="paragraph">
<p>So when we first ask it for next-value, we&#8217;d get 1.
We then assume that the valid pool would be the values from 1-20 inclusive.</p>
</div>
<div class="paragraph">
<p>The next call to the sequence would result in 21, which would define 21-40 as the valid range. And so on.
The "lo" part of the name indicates that the value from the database table/sequence is interpreted as the pool lo(w) end.</p>
</div>
</dd>
<dt class="hdlist1">pooled</dt>
<dd>
<p>Just like pooled-lo, except that here the value from the table/sequence is interpreted as the high end of the value pool.</p>
</dd>
<dt class="hdlist1">hilo; legacy-hilo</dt>
<dd>
<p>Define a custom algorithm for generating pools of values based on a single value from a table or sequence.</p>
<div class="paragraph">
<p>These optimizers are not recommended for use. They are maintained (and mentioned) here simply for use by legacy applications that used these strategies previously.</p>
</div>
</dd>
</dl>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Applications can also implement and use their own optimizer strategies, as defined by the <code>org.hibernate.id.enhanced.Optimizer</code> contract.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-generators-GenericGenerator">Using <code>@GenericGenerator</code></h4>
<div class="paragraph">
<p><code>@GenericGenerator</code> allows integration of any Hibernate <code>org.hibernate.id.IdentifierGenerator</code> implementation, including any of the specific ones discussed here and any custom ones.</p>
</div>
<div class="paragraph">
<p>To make use of the pooled or pooled-lo optimizers,
the entity mapping must use the <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/GenericGenerator.html"><code>@GenericGenerator</code></a> annotation:</p>
</div>
<div id="identifiers-generators-pooled-lo-optimizer-mapping-example" class="exampleblock">
<div class="title">Example 138. Pooled-lo optimizer mapping using <code>@GenericGenerator</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Product")
public static class Product {

    @Id
    @GeneratedValue(
        strategy = GenerationType.SEQUENCE,
        generator = "product_generator"
    )
    @GenericGenerator(
        name = "product_generator",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
            @Parameter(name = "sequence_name", value = "product_sequence"),
            @Parameter(name = "initial_value", value = "1"),
            @Parameter(name = "increment_size", value = "3"),
            @Parameter(name = "optimizer", value = "pooled-lo")
        }
    )
    private Long id;

    @Column(name = "p_name")
    private String name;

    @Column(name = "p_number")
    private String number;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Now, when saving 5 <code>Person</code> entities and flushing the Persistence Context after every 3 entities:</p>
</div>
<div id="identifiers-generators-pooled-lo-optimizer-persist-example" class="exampleblock">
<div class="title">Example 139. Pooled-lo optimizer mapping using <code>@GenericGenerator</code> mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">for ( long i = 1; i &lt;= 5; i++ ) {
    if(i % 3 == 0) {
        entityManager.flush();
    }
    Product product = new Product();
    product.setName( String.format( "Product %d", i ) );
    product.setNumber( String.format( "P_100_%d", i ) );
    entityManager.persist( product );
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">CALL NEXT VALUE FOR product_sequence

INSERT INTO Product (p_name, p_number, id)
VALUES (?, ?, ?)

-- binding parameter [1] as [VARCHAR] - [Product 1]
-- binding parameter [2] as [VARCHAR] - [P_100_1]
-- binding parameter [3] as [BIGINT]  - [1]

INSERT INTO Product (p_name, p_number, id)
VALUES (?, ?, ?)

-- binding parameter [1] as [VARCHAR] - [Product 2]
-- binding parameter [2] as [VARCHAR] - [P_100_2]
-- binding parameter [3] as [BIGINT]  - [2]

CALL NEXT VALUE FOR product_sequence

INSERT INTO Product (p_name, p_number, id)
VALUES (?, ?, ?)

-- binding parameter [1] as [VARCHAR] - [Product 3]
-- binding parameter [2] as [VARCHAR] - [P_100_3]
-- binding parameter [3] as [BIGINT]  - [3]

INSERT INTO Product (p_name, p_number, id)
VALUES (?, ?, ?)

-- binding parameter [1] as [VARCHAR] - [Product 4]
-- binding parameter [2] as [VARCHAR] - [P_100_4]
-- binding parameter [3] as [BIGINT]  - [4]

INSERT INTO Product (p_name, p_number, id)
VALUES (?, ?, ?)

-- binding parameter [1] as [VARCHAR] - [Product 5]
-- binding parameter [2] as [VARCHAR] - [P_100_5]
-- binding parameter [3] as [BIGINT]  - [5]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see from the list of generated SQL statements, you can insert 3 entities for one database sequence call.
This way, the pooled and the pooled-lo optimizers allow you to reduce the number of database roundtrips, therefore reducing the overall transaction response time.</p>
</div>
</div>
<div class="sect3">
<h4 id="identifiers-derived">Derived Identifiers</h4>
<div class="paragraph">
<p>JPA 2.0 added support for derived identifiers which allow an entity to borrow the identifier from a many-to-one or one-to-one association.</p>
</div>
<div id="identifiers-derived-mapsid" class="exampleblock">
<div class="title">Example 140. Derived identifier with <code>@MapsId</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Person  {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String registrationNumber;

    public Person() {}

    public Person(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public Long getId() {
        return id;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }
}

@Entity
public class PersonDetails  {

    @Id
    private Long id;

    private String nickName;

    @ManyToOne
    @MapsId
    private Person person;

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In the example above, the <code>PersonDetails</code> entity uses the <code>id</code> column for both the entity identifier and for the many-to-one association to the <code>Person</code> entity.
The value of the <code>PersonDetails</code> entity identifier is "derived" from the identifier of its parent <code>Person</code> entity.
The <code>@MapsId</code> annotation can also reference columns from an <code>@EmbeddedId</code> identifier as well.</p>
</div>
<div class="paragraph">
<p>The previous example can also be mapped using <code>@PrimaryKeyJoinColumn</code>.</p>
</div>
<div id="identifiers-derived-primarykeyjoincolumn" class="exampleblock">
<div class="title">Example 141. Derived identifier <code>@PrimaryKeyJoinColumn</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class PersonDetails  {

    @Id
    private Long id;

    private String nickName;

    @ManyToOne
    @PrimaryKeyJoinColumn
    private Person person;

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
        this.id = person.getId();
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Unlike <code>@MapsId</code>, the application developer is responsible for ensuring that the identifier and the many-to-one (or one-to-one) association are in sync.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="associations">Associations</h3>
<div class="paragraph">
<p>Associations describe how two or more entities form a relationship based on a database joining semantics.</p>
</div>
<div class="sect3">
<h4 id="associations-many-to-one"><code>@ManyToOne</code></h4>
<div class="paragraph">
<p><code>@ManyToOne</code> is the most common association, having a direct equivalent in the relational database as well (e.g. foreign key),
and so it establishes a relationship between a child entity and a parent.</p>
</div>
<div id="associations-many-to-one-example" class="exampleblock">
<div class="title">Example 142. <code>@ManyToOne</code> association</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    @GeneratedValue
    private Long id;

    public Person() {
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`number`")
    private String number;

    @ManyToOne
    @JoinColumn(name = "person_id",
            foreignKey = @ForeignKey(name = "PERSON_ID_FK")
    )
    private Person person;

    public Phone() {
    }

    public Phone(String number) {
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getNumber() {
        return number;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    person_id BIGINT ,
    PRIMARY KEY ( id )
 )

ALTER TABLE Phone
ADD CONSTRAINT PERSON_ID_FK
FOREIGN KEY (person_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Each entity has a lifecycle of its own. Once the <code>@ManyToOne</code> association is set, Hibernate will set the associated database foreign key column.</p>
</div>
<div id="associations-many-to-one-lifecycle-example" class="exampleblock">
<div class="title">Example 143. <code>@ManyToOne</code> association lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = new Person();
entityManager.persist( person );

Phone phone = new Phone( "123-456-7890" );
phone.setPerson( person );
entityManager.persist( phone );

entityManager.flush();
phone.setPerson( null );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Person ( id )
VALUES ( 1 )

INSERT INTO Phone ( number, person_id, id )
VALUES ( '123-456-7890', 1, 2 )

UPDATE Phone
SET    number = '123-456-7890',
       person_id = NULL
WHERE  id = 2</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="associations-one-to-many"><code>@OneToMany</code></h4>
<div class="paragraph">
<p>The <code>@OneToMany</code> association links a parent entity with one or more child entities.
If the <code>@OneToMany</code> doesn&#8217;t have a mirroring <code>@ManyToOne</code> association on the child side, the <code>@OneToMany</code> association is unidirectional.
If there is a <code>@ManyToOne</code> association on the child side, the <code>@OneToMany</code> association is bidirectional and the application developer can navigate this relationship from both ends.</p>
</div>
<div class="sect4">
<h5 id="associations-one-to-many-unidirectional">Unidirectional <code>@OneToMany</code></h5>
<div class="paragraph">
<p>When using a unidirectional <code>@OneToMany</code> association, Hibernate resorts to using a link table between the two joining entities.</p>
</div>
<div id="associations-one-to-many-unidirectional-example" class="exampleblock">
<div class="title">Example 144. Unidirectional <code>@OneToMany</code> association</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    @GeneratedValue
    private Long id;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();

    public Person() {
    }

    public List&lt;Phone&gt; getPhones() {
        return phones;
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`number`")
    private String number;

    public Phone() {
    }

    public Phone(String number) {
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getNumber() {
        return number;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE Person_Phone (
    Person_id BIGINT NOT NULL ,
    phones_id BIGINT NOT NULL
)

CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    PRIMARY KEY ( id )
)

ALTER TABLE Person_Phone
ADD CONSTRAINT UK_9uhc5itwc9h5gcng944pcaslf
UNIQUE (phones_id)

ALTER TABLE Person_Phone
ADD CONSTRAINT FKr38us2n8g5p9rj0b494sd3391
FOREIGN KEY (phones_id) REFERENCES Phone

ALTER TABLE Person_Phone
ADD CONSTRAINT FK2ex4e4p7w1cj310kg2woisjl2
FOREIGN KEY (Person_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The <code>@OneToMany</code> association is by definition a parent association, even if it&#8217;s a unidirectional or a bidirectional one.
Only the parent side of an association makes sense to cascade its entity state transitions to children.</p>
</div>
</td>
</tr>
</table>
</div>
<div id="associations-one-to-many-unidirectional-lifecycle-example" class="exampleblock">
<div class="title">Example 145. Cascading <code>@OneToMany</code> association</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = new Person();
Phone phone1 = new Phone( "123-456-7890" );
Phone phone2 = new Phone( "321-654-0987" );

person.getPhones().add( phone1 );
person.getPhones().add( phone2 );
entityManager.persist( person );
entityManager.flush();

person.getPhones().remove( phone1 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Person
       ( id )
VALUES ( 1 )

INSERT INTO Phone
       ( number, id )
VALUES ( '123 - 456 - 7890', 2 )

INSERT INTO Phone
       ( number, id )
VALUES ( '321 - 654 - 0987', 3 )

INSERT INTO Person_Phone
       ( Person_id, phones_id )
VALUES ( 1, 2 )

INSERT INTO Person_Phone
       ( Person_id, phones_id )
VALUES ( 1, 3 )

DELETE FROM Person_Phone
WHERE  Person_id = 1

INSERT INTO Person_Phone
       ( Person_id, phones_id )
VALUES ( 1, 3 )

DELETE FROM Phone
WHERE  id = 2</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When persisting the <code>Person</code> entity, the cascade will propagate the persist operation to the underlying <code>Phone</code> children as well.
Upon removing a <code>Phone</code> from the phones collection, the association row is deleted from the link table, and the <code>orphanRemoval</code> attribute will trigger a <code>Phone</code> removal as well.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The unidirectional associations are not very efficient when it comes to removing child entities.
In this particular example, upon flushing the persistence context, Hibernate deletes all database child entries and reinserts the ones that are still found in the in-memory persistence context.</p>
</div>
<div class="paragraph">
<p>On the other hand, a bidirectional <code>@OneToMany</code> association is much more efficient because the child entity controls the association.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect4">
<h5 id="associations-one-to-many-bidirectional">Bidirectional <code>@OneToMany</code></h5>
<div class="paragraph">
<p>The bidirectional <code>@OneToMany</code> association also requires a <code>@ManyToOne</code> association on the child side.
Although the Domain Model exposes two sides to navigate this association, behind the scenes, the relational database has only one foreign key for this relationship.</p>
</div>
<div class="paragraph">
<p>Every bidirectional association must have one owning side only (the child side), the other one being referred to as the <em>inverse</em> (or the <code>mappedBy</code>) side.</p>
</div>
<div id="associations-one-to-many-bidirectional-example" class="exampleblock">
<div class="title">Example 146. <code>@OneToMany</code> association mappedBy the <code>@ManyToOne</code> side</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    @GeneratedValue
    private Long id;
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
    private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public List&lt;Phone&gt; getPhones() {
        return phones;
    }

    public void addPhone(Phone phone) {
        phones.add( phone );
        phone.setPerson( this );
    }

    public void removePhone(Phone phone) {
        phones.remove( phone );
        phone.setPerson( null );
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    @Column(name = "`number`", unique = true)
    private String number;

    @ManyToOne
    private Person person;

    public Phone() {
    }

    public Phone(String number) {
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getNumber() {
        return number;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Phone phone = (Phone) o;
        return Objects.equals( number, phone.number );
    }

    @Override
    public int hashCode() {
        return Objects.hash( number );
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    person_id BIGINT ,
    PRIMARY KEY ( id )
)

ALTER TABLE Phone
ADD CONSTRAINT UK_l329ab0g4c1t78onljnxmbnp6
UNIQUE (number)

ALTER TABLE Phone
ADD CONSTRAINT FKmw13yfsjypiiq0i1osdkaeqpg
FOREIGN KEY (person_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Whenever a bidirectional association is formed, the application developer must make sure both sides are in-sync at all times.
The <code>addPhone()</code> and <code>removePhone()</code> are utilities methods that synchronize both ends whenever a child element is added or removed.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Because the <code>Phone</code> class has a <code>@NaturalId</code> column (the phone number being unique),
the <code>equals()</code> and the <code>hashCode()</code> can make use of this property, and so the <code>removePhone()</code> logic is reduced to the <code>remove()</code> Java <code>Collection</code> method.</p>
</div>
<div id="associations-one-to-many-bidirectional-lifecycle-example" class="exampleblock">
<div class="title">Example 147. Bidirectional <code>@OneToMany</code> with an owner <code>@ManyToOne</code> side lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = new Person();
Phone phone1 = new Phone( "123-456-7890" );
Phone phone2 = new Phone( "321-654-0987" );

person.addPhone( phone1 );
person.addPhone( phone2 );
entityManager.persist( person );
entityManager.flush();

person.removePhone( phone1 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Phone
       ( number, person_id, id )
VALUES ( '123-456-7890', NULL, 2 )

INSERT INTO Phone
       ( number, person_id, id )
VALUES ( '321-654-0987', NULL, 3 )

DELETE FROM Phone
WHERE  id = 2</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Unlike the unidirectional <code>@OneToMany</code>, the bidirectional association is much more efficient when managing the collection persistence state.
Every element removal only requires a single update (in which the foreign key column is set to <code>NULL</code>), and,
if the child entity lifecycle is bound to its owning parent so that the child cannot exist without its parent,
then we can annotate the association with the <code>orphan-removal</code> attribute and disassociating the child will trigger a delete statement on the actual child table row as well.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="associations-one-to-one"><code>@OneToOne</code></h4>
<div class="paragraph">
<p>The <code>@OneToOne</code> association can either be unidirectional or bidirectional.
A unidirectional association follows the relational database foreign key semantics, the client-side owning the relationship.
A bidirectional association features a <code>mappedBy</code> <code>@OneToOne</code> parent side too.</p>
</div>
<div class="sect4">
<h5 id="associations-one-to-one-unidirectional">Unidirectional <code>@OneToOne</code></h5>
<div id="associations-one-to-one-unidirectional-example" class="exampleblock">
<div class="title">Example 148. Unidirectional <code>@OneToOne</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Phone")
public static class Phone {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`number`")
    private String number;

    @OneToOne
    @JoinColumn(name = "details_id")
    private PhoneDetails details;

    public Phone() {
    }

    public Phone(String number) {
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getNumber() {
        return number;
    }

    public PhoneDetails getDetails() {
        return details;
    }

    public void setDetails(PhoneDetails details) {
        this.details = details;
    }
}

@Entity(name = "PhoneDetails")
public static class PhoneDetails {

    @Id
    @GeneratedValue
    private Long id;

    private String provider;

    private String technology;

    public PhoneDetails() {
    }

    public PhoneDetails(String provider, String technology) {
        this.provider = provider;
        this.technology = technology;
    }

    public String getProvider() {
        return provider;
    }

    public String getTechnology() {
        return technology;
    }

    public void setTechnology(String technology) {
        this.technology = technology;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    details_id BIGINT ,
    PRIMARY KEY ( id )
)

CREATE TABLE PhoneDetails (
    id BIGINT NOT NULL ,
    provider VARCHAR(255) ,
    technology VARCHAR(255) ,
    PRIMARY KEY ( id )
)

ALTER TABLE Phone
ADD CONSTRAINT FKnoj7cj83ppfqbnvqqa5kolub7
FOREIGN KEY (details_id) REFERENCES PhoneDetails</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>From a relational database point of view, the underlying schema is identical to the unidirectional <code>@ManyToOne</code> association,
as the client-side controls the relationship based on the foreign key column.</p>
</div>
<div class="paragraph">
<p>But then, it&#8217;s unusual to consider the <code>Phone</code> as a client-side and the <code>PhoneDetails</code> as the parent-side because the details cannot exist without an actual phone.
A much more natural mapping would be if the <code>Phone</code> were the parent-side, therefore pushing the foreign key into the <code>PhoneDetails</code> table.
This mapping requires a bidirectional <code>@OneToOne</code> association as you can see in the following example:</p>
</div>
</div>
<div class="sect4">
<h5 id="associations-one-to-one-bidirectional">Bidirectional <code>@OneToOne</code></h5>
<div id="associations-one-to-one-bidirectional-example" class="exampleblock">
<div class="title">Example 149. Bidirectional <code>@OneToOne</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Phone")
public static class Phone {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`number`")
    private String number;

    @OneToOne(mappedBy = "phone", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private PhoneDetails details;

    public Phone() {
    }

    public Phone(String number) {
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getNumber() {
        return number;
    }

    public PhoneDetails getDetails() {
        return details;
    }

    public void addDetails(PhoneDetails details) {
        details.setPhone( this );
        this.details = details;
    }

    public void removeDetails() {
        if ( details != null ) {
            details.setPhone( null );
            this.details = null;
        }
    }
}

@Entity(name = "PhoneDetails")
public static class PhoneDetails {

    @Id
    @GeneratedValue
    private Long id;

    private String provider;

    private String technology;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "phone_id")
    private Phone phone;

    public PhoneDetails() {
    }

    public PhoneDetails(String provider, String technology) {
        this.provider = provider;
        this.technology = technology;
    }

    public String getProvider() {
        return provider;
    }

    public String getTechnology() {
        return technology;
    }

    public void setTechnology(String technology) {
        this.technology = technology;
    }

    public Phone getPhone() {
        return phone;
    }

    public void setPhone(Phone phone) {
        this.phone = phone;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    PRIMARY KEY ( id )
)

CREATE TABLE PhoneDetails (
    id BIGINT NOT NULL ,
    provider VARCHAR(255) ,
    technology VARCHAR(255) ,
    phone_id BIGINT ,
    PRIMARY KEY ( id )
)

ALTER TABLE PhoneDetails
ADD CONSTRAINT FKeotuev8ja8v0sdh29dynqj05p
FOREIGN KEY (phone_id) REFERENCES Phone</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This time, the <code>PhoneDetails</code> owns the association, and, like any bidirectional association, the parent-side can propagate its lifecycle to the child-side through cascading.</p>
</div>
<div id="associations-one-to-one-bidirectional-lifecycle-example" class="exampleblock">
<div class="title">Example 150. Bidirectional <code>@OneToOne</code> lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Phone phone = new Phone( "123-456-7890" );
PhoneDetails details = new PhoneDetails( "T-Mobile", "GSM" );

phone.addDetails( details );
entityManager.persist( phone );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Phone ( number, id )
VALUES ( '123 - 456 - 7890', 1 )

INSERT INTO PhoneDetails ( phone_id, provider, technology, id )
VALUES ( 1, 'T - Mobile, GSM', 2 )</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When using a bidirectional <code>@OneToOne</code> association, Hibernate enforces the unique constraint upon fetching the child-side.
If there are more than one children associated with the same parent, Hibernate will throw a <code>org.hibernate.exception.ConstraintViolationException</code>.
Continuing the previous example, when adding another <code>PhoneDetails</code>, Hibernate validates the uniqueness constraint when reloading the <code>Phone</code> object.</p>
</div>
<div id="associations-one-to-one-bidirectional-constraint-example" class="exampleblock">
<div class="title">Example 151. Bidirectional <code>@OneToOne</code> unique constraint</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">PhoneDetails otherDetails = new PhoneDetails( "T-Mobile", "CDMA" );
otherDetails.setPhone( phone );
entityManager.persist( otherDetails );
entityManager.flush();
entityManager.clear();

//throws javax.persistence.PersistenceException: org.hibernate.HibernateException: More than one row with the given identifier was found: 1
phone = entityManager.find( Phone.class, phone.getId() );</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="associations-many-to-many"><code>@ManyToMany</code></h4>
<div class="paragraph">
<p>The <code>@ManyToMany</code> association requires a link table that joins two entities.
Like the <code>@OneToMany</code> association, <code>@ManyToMany</code> can be a either unidirectional or bidirectional.</p>
</div>
<div class="sect4">
<h5 id="associations-many-to-many-unidirectional">Unidirectional <code>@ManyToMany</code></h5>
<div id="associations-many-to-many-unidirectional-example" class="exampleblock">
<div class="title">Example 152. Unidirectional <code>@ManyToMany</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    @GeneratedValue
    private Long id;
    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List&lt;Address&gt; addresses = new ArrayList&lt;&gt;();

    public Person() {
    }

    public List&lt;Address&gt; getAddresses() {
        return addresses;
    }
}

@Entity(name = "Address")
public static class Address {

    @Id
    @GeneratedValue
    private Long id;

    private String street;

    @Column(name = "`number`")
    private String number;

    public Address() {
    }

    public Address(String street, String number) {
        this.street = street;
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getStreet() {
        return street;
    }

    public String getNumber() {
        return number;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Address (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    street VARCHAR(255) ,
    PRIMARY KEY ( id )
)

CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE Person_Address (
    Person_id BIGINT NOT NULL ,
    addresses_id BIGINT NOT NULL
)

ALTER TABLE Person_Address
ADD CONSTRAINT FKm7j0bnabh2yr0pe99il1d066u
FOREIGN KEY (addresses_id) REFERENCES Address

ALTER TABLE Person_Address
ADD CONSTRAINT FKba7rc9qe2vh44u93u0p2auwti
FOREIGN KEY (Person_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Just like with unidirectional <code>@OneToMany</code> associations, the link table is controlled by the owning side.</p>
</div>
<div class="paragraph">
<p>When an entity is removed from the <code>@ManyToMany</code> collection, Hibernate simply deletes the joining record in the link table.
Unfortunately, this operation requires removing all entries associated with a given parent and recreating the ones that are listed in the current running persistent context.</p>
</div>
<div id="associations-many-to-many-unidirectional-lifecycle-example" class="exampleblock">
<div class="title">Example 153. Unidirectional <code>@ManyToMany</code> lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person1 = new Person();
Person person2 = new Person();

Address address1 = new Address( "12th Avenue", "12A" );
Address address2 = new Address( "18th Avenue", "18B" );

person1.getAddresses().add( address1 );
person1.getAddresses().add( address2 );

person2.getAddresses().add( address1 );

entityManager.persist( person1 );
entityManager.persist( person2 );

entityManager.flush();

person1.getAddresses().remove( address1 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Person ( id )
VALUES ( 1 )

INSERT INTO Address ( number, street, id )
VALUES ( '12A', '12th Avenue', 2 )

INSERT INTO Address ( number, street, id )
VALUES ( '18B', '18th Avenue', 3 )

INSERT INTO Person ( id )
VALUES ( 4 )

INSERT INTO Person_Address ( Person_id, addresses_id )
VALUES ( 1, 2 )
INSERT INTO Person_Address ( Person_id, addresses_id )
VALUES ( 1, 3 )
INSERT INTO Person_Address ( Person_id, addresses_id )
VALUES ( 4, 2 )

DELETE FROM Person_Address
WHERE  Person_id = 1

INSERT INTO Person_Address ( Person_id, addresses_id )
VALUES ( 1, 3 )</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>For <code>@ManyToMany</code> associations, the <code>REMOVE</code> entity state transition doesn&#8217;t make sense to be cascaded because it will propagate beyond the link table.
Since the other side might be referenced by other entities on the parent-side, the automatic removal might end up in a <code>ConstraintViolationException</code>.</p>
</div>
<div class="paragraph">
<p>For example, if <code>@ManyToMany(cascade = CascadeType.ALL)</code> was defined and the first person would be deleted,
Hibernate would throw an exception because another person is still associated with the address that&#8217;s being deleted.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person1 = entityManager.find(Person.class, personId);
entityManager.remove(person1);

Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: foreign key no action; FKM7J0BNABH2YR0PE99IL1D066U table: PERSON_ADDRESS</code></pre>
</div>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>By simply removing the parent-side, Hibernate can safely remove the associated link records as you can see in the following example:</p>
</div>
<div id="associations-many-to-many-unidirectional-remove-example" class="exampleblock">
<div class="title">Example 154. Unidirectional <code>@ManyToMany</code> entity removal</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person1 = entityManager.find( Person.class, personId );
entityManager.remove( person1 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">DELETE FROM Person_Address
WHERE  Person_id = 1

DELETE FROM Person
WHERE  id = 1</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="associations-many-to-many-bidirectional">Bidirectional <code>@ManyToMany</code></h5>
<div class="paragraph">
<p>A bidirectional <code>@ManyToMany</code> association has an owning and a <code>mappedBy</code> side.
To preserve synchronicity between both sides, it&#8217;s good practice to provide helper methods for adding or removing child entities.</p>
</div>
<div id="associations-many-to-many-bidirectional-example" class="exampleblock">
<div class="title">Example 155. Bidirectional <code>@ManyToMany</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String registrationNumber;
    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List&lt;Address&gt; addresses = new ArrayList&lt;&gt;();

    public Person() {
    }

    public Person(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public List&lt;Address&gt; getAddresses() {
        return addresses;
    }

    public void addAddress(Address address) {
        addresses.add( address );
        address.getOwners().add( this );
    }

    public void removeAddress(Address address) {
        addresses.remove( address );
        address.getOwners().remove( this );
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Person person = (Person) o;
        return Objects.equals( registrationNumber, person.registrationNumber );
    }

    @Override
    public int hashCode() {
        return Objects.hash( registrationNumber );
    }
}

@Entity(name = "Address")
public static class Address {

    @Id
    @GeneratedValue
    private Long id;

    private String street;

    @Column(name = "`number`")
    private String number;

    private String postalCode;

    @ManyToMany(mappedBy = "addresses")
    private List&lt;Person&gt; owners = new ArrayList&lt;&gt;();

    public Address() {
    }

    public Address(String street, String number, String postalCode) {
        this.street = street;
        this.number = number;
        this.postalCode = postalCode;
    }

    public Long getId() {
        return id;
    }

    public String getStreet() {
        return street;
    }

    public String getNumber() {
        return number;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public List&lt;Person&gt; getOwners() {
        return owners;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Address address = (Address) o;
        return Objects.equals( street, address.street ) &amp;&amp;
                Objects.equals( number, address.number ) &amp;&amp;
                Objects.equals( postalCode, address.postalCode );
    }

    @Override
    public int hashCode() {
        return Objects.hash( street, number, postalCode );
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Address (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    postalCode VARCHAR(255) ,
    street VARCHAR(255) ,
    PRIMARY KEY ( id )
)

CREATE TABLE Person (
    id BIGINT NOT NULL ,
    registrationNumber VARCHAR(255) ,
    PRIMARY KEY ( id )
)

CREATE TABLE Person_Address (
    owners_id BIGINT NOT NULL ,
    addresses_id BIGINT NOT NULL
)

ALTER TABLE Person
ADD CONSTRAINT UK_23enodonj49jm8uwec4i7y37f
UNIQUE (registrationNumber)

ALTER TABLE Person_Address
ADD CONSTRAINT FKm7j0bnabh2yr0pe99il1d066u
FOREIGN KEY (addresses_id) REFERENCES Address

ALTER TABLE Person_Address
ADD CONSTRAINT FKbn86l24gmxdv2vmekayqcsgup
FOREIGN KEY (owners_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>With the helper methods in place, the synchronicity management can be simplified, as you can see in the following example:</p>
</div>
<div id="associations-many-to-many-bidirectional-lifecycle-example" class="exampleblock">
<div class="title">Example 156. Bidirectional <code>@ManyToMany</code> lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person1 = new Person( "ABC-123" );
Person person2 = new Person( "DEF-456" );

Address address1 = new Address( "12th Avenue", "12A", "4005A" );
Address address2 = new Address( "18th Avenue", "18B", "4007B" );

person1.addAddress( address1 );
person1.addAddress( address2 );

person2.addAddress( address1 );

entityManager.persist( person1 );
entityManager.persist( person2 );

entityManager.flush();

person1.removeAddress( address1 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Person ( registrationNumber, id )
VALUES ( 'ABC-123', 1 )

INSERT INTO Address ( number, postalCode, street, id )
VALUES ( '12A', '4005A', '12th Avenue', 2 )

INSERT INTO Address ( number, postalCode, street, id )
VALUES ( '18B', '4007B', '18th Avenue', 3 )

INSERT INTO Person ( registrationNumber, id )
VALUES ( 'DEF-456', 4 )

INSERT INTO Person_Address ( owners_id, addresses_id )
VALUES ( 1, 2 )

INSERT INTO Person_Address ( owners_id, addresses_id )
VALUES ( 1, 3 )

INSERT INTO Person_Address ( owners_id, addresses_id )
VALUES ( 4, 2 )

DELETE FROM Person_Address
WHERE  owners_id = 1

INSERT INTO Person_Address ( owners_id, addresses_id )
VALUES ( 1, 3 )</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>If a bidirectional <code>@OneToMany</code> association performs better when removing or changing the order of child elements,
the <code>@ManyToMany</code> relationship cannot benefit from such an optimization because the foreign key side is not in control.
To overcome this limitation, the link table must be directly exposed and the <code>@ManyToMany</code> association split into two bidirectional <code>@OneToMany</code> relationships.</p>
</div>
</div>
<div class="sect4">
<h5 id="associations-many-to-many-bidirectional-with-link-entity">Bidirectional many-to-many with a link entity</h5>
<div class="paragraph">
<p>To most natural <code>@ManyToMany</code> association follows the same logic employed by the database schema,
and the link table has an associated entity which controls the relationship for both sides that need to be joined.</p>
</div>
<div id="associations-many-to-many-bidirectional-with-link-entity-example" class="exampleblock">
<div class="title">Example 157. Bidirectional many-to-many with link entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String registrationNumber;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
    private List&lt;PersonAddress&gt; addresses = new ArrayList&lt;&gt;();

    public Person() {
    }

    public Person(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public Long getId() {
        return id;
    }

    public List&lt;PersonAddress&gt; getAddresses() {
        return addresses;
    }

    public void addAddress(Address address) {
        PersonAddress personAddress = new PersonAddress( this, address );
        addresses.add( personAddress );
        address.getOwners().add( personAddress );
    }

    public void removeAddress(Address address) {
        PersonAddress personAddress = new PersonAddress( this, address );
        address.getOwners().remove( personAddress );
        addresses.remove( personAddress );
        personAddress.setPerson( null );
        personAddress.setAddress( null );
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Person person = (Person) o;
        return Objects.equals( registrationNumber, person.registrationNumber );
    }

    @Override
    public int hashCode() {
        return Objects.hash( registrationNumber );
    }
}

@Entity(name = "PersonAddress")
public static class PersonAddress implements Serializable {

    @Id
    @ManyToOne
    private Person person;

    @Id
    @ManyToOne
    private Address address;

    public PersonAddress() {
    }

    public PersonAddress(Person person, Address address) {
        this.person = person;
        this.address = address;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        PersonAddress that = (PersonAddress) o;
        return Objects.equals( person, that.person ) &amp;&amp;
                Objects.equals( address, that.address );
    }

    @Override
    public int hashCode() {
        return Objects.hash( person, address );
    }
}

@Entity(name = "Address")
public static class Address implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    private String street;

    @Column(name = "`number`")
    private String number;

    private String postalCode;

    @OneToMany(mappedBy = "address", cascade = CascadeType.ALL, orphanRemoval = true)
    private List&lt;PersonAddress&gt; owners = new ArrayList&lt;&gt;();

    public Address() {
    }

    public Address(String street, String number, String postalCode) {
        this.street = street;
        this.number = number;
        this.postalCode = postalCode;
    }

    public Long getId() {
        return id;
    }

    public String getStreet() {
        return street;
    }

    public String getNumber() {
        return number;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public List&lt;PersonAddress&gt; getOwners() {
        return owners;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Address address = (Address) o;
        return Objects.equals( street, address.street ) &amp;&amp;
                Objects.equals( number, address.number ) &amp;&amp;
                Objects.equals( postalCode, address.postalCode );
    }

    @Override
    public int hashCode() {
        return Objects.hash( street, number, postalCode );
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Address (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    postalCode VARCHAR(255) ,
    street VARCHAR(255) ,
    PRIMARY KEY ( id )
)

CREATE TABLE Person (
    id BIGINT NOT NULL ,
    registrationNumber VARCHAR(255) ,
    PRIMARY KEY ( id )
)

CREATE TABLE PersonAddress (
    person_id BIGINT NOT NULL ,
    address_id BIGINT NOT NULL ,
    PRIMARY KEY ( person_id, address_id )
)

ALTER TABLE Person
ADD CONSTRAINT UK_23enodonj49jm8uwec4i7y37f
UNIQUE (registrationNumber)

ALTER TABLE PersonAddress
ADD CONSTRAINT FK8b3lru5fyej1aarjflamwghqq
FOREIGN KEY (person_id) REFERENCES Person

ALTER TABLE PersonAddress
ADD CONSTRAINT FK7p69mgialumhegyl4byrh65jk
FOREIGN KEY (address_id) REFERENCES Address</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Both the <code>Person</code> and the <code>Address</code> have a <code>mappedBy</code> <code>@OneToMany</code> side, while the <code>PersonAddress</code> owns the <code>person</code> and the <code>address</code> <code>@ManyToOne</code> associations.
Because this mapping is formed out of two bidirectional associations, the helper methods are even more relevant.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The aforementioned example uses a Hibernate specific mapping for the link entity since JPA doesn&#8217;t allow building a composite identifier out of multiple <code>@ManyToOne</code> associations.
For more details, see the <a href="chapters/domain/identifiers.html#identifiers-composite-associations">Composite identifiers - associations</a> section.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The entity state transitions are better managed than in the previous bidirectional <code>@ManyToMany</code> case.</p>
</div>
<div id="associations-many-to-many-bidirectional-with-link-entity-lifecycle-example" class="exampleblock">
<div class="title">Example 158. Bidirectional many-to-many with link entity lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person1 = new Person( "ABC-123" );
Person person2 = new Person( "DEF-456" );

Address address1 = new Address( "12th Avenue", "12A", "4005A" );
Address address2 = new Address( "18th Avenue", "18B", "4007B" );

entityManager.persist( person1 );
entityManager.persist( person2 );

entityManager.persist( address1 );
entityManager.persist( address2 );

person1.addAddress( address1 );
person1.addAddress( address2 );

person2.addAddress( address1 );

entityManager.flush();

log.info( "Removing address" );
person1.removeAddress( address1 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT  INTO Person ( registrationNumber, id )
VALUES  ( 'ABC-123', 1 )

INSERT  INTO Person ( registrationNumber, id )
VALUES  ( 'DEF-456', 2 )

INSERT  INTO Address ( number, postalCode, street, id )
VALUES  ( '12A', '4005A', '12th Avenue', 3 )

INSERT  INTO Address ( number, postalCode, street, id )
VALUES  ( '18B', '4007B', '18th Avenue', 4 )

INSERT  INTO PersonAddress ( person_id, address_id )
VALUES  ( 1, 3 )

INSERT  INTO PersonAddress ( person_id, address_id )
VALUES  ( 1, 4 )

INSERT  INTO PersonAddress ( person_id, address_id )
VALUES  ( 2, 3 )

DELETE  FROM PersonAddress
WHERE   person_id = 1 AND address_id = 3</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>There is only one delete statement executed because, this time, the association is controlled by the <code>@ManyToOne</code> side which only has to monitor the state of the underlying foreign key relationship to trigger the right DML statement.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="associations-not-found"><code>@NotFound</code> association mapping</h4>
<div class="paragraph">
<p>When dealing with associations which are not enforced by a Foreign Key,
it&#8217;s possible to bump into inconsistencies if the child record cannot reference a parent entity.</p>
</div>
<div class="paragraph">
<p>By default, Hibernate will complain whenever a child association references a non-existing parent record.
However, you can configure this behavior so that Hibernate can ignore such an Exception and simply assign <code>null</code> as a parent object referenced.</p>
</div>
<div class="paragraph">
<p>To ignore non-existing parent entity references, even though not really recommended, it&#8217;s possible to use the annotation <code>org.hibernate.annotation.NotFound</code> annotation with a value of <code>org.hibernate.annotations.NotFoundAction.IGNORE</code>.</p>
</div>
<div class="paragraph">
<p>Considering the following <code>City</code> and <code>Person</code> entity mappings:</p>
</div>
<div id="associations-not-found-domain-model-example" class="exampleblock">
<div class="title">Example 159. <code>@NotFound</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
@Table( name = "Person" )
public static class Person {

    @Id
    private Long id;

    private String name;

    private String cityName;

    @ManyToOne( fetch = FetchType.LAZY )
    @NotFound ( action = NotFoundAction.IGNORE )
    @JoinColumn(
        name = "cityName",
        referencedColumnName = "name",
        insertable = false,
        updatable = false
    )
    private City city;

    //Getters and setters are omitted for brevity

}

@Entity
@Table( name = "City" )
public static class City implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>If we have the following entities in our database:</p>
</div>
<div id="associations-not-found-persist-example" class="exampleblock">
<div class="title">Example 160. <code>@NotFound</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">City _NewYork = new City();
_NewYork.setName( "New York" );
entityManager.persist( _NewYork );

Person person = new Person();
person.setId( 1L );
person.setName( "John Doe" );
person.setCityName( "New York" );
entityManager.persist( person );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When loading the <code>Person</code> entity, Hibernate is able to locate the associated <code>City</code> parent entity:</p>
</div>
<div id="associations-not-found-find-example" class="exampleblock">
<div class="title">Example 161. <code>@NotFound</code> find existing entity example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = entityManager.find( Person.class, 1L );
assertEquals( "New York", person.getCity().getName() );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>However, if we change the <code>cityName</code> attribute to a non-existing city:</p>
</div>
<div id="associations-not-found-non-existing-persist-example" class="exampleblock">
<div class="title">Example 162. <code>@NotFound</code> change to non-existing City example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">person.setCityName( "Atlantis" );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Hibernate is not going to throw any exception, and it will assign a value of <code>null</code> for the non-existing <code>City</code> entity reference:</p>
</div>
<div id="associations-not-found-non-existing-find-example" class="exampleblock">
<div class="title">Example 163. <code>@NotFound</code> find non-existing City example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = entityManager.find( Person.class, 1L );

assertEquals( "Atlantis", person.getCityName() );
assertNull( null, person.getCity() );</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="collections">Collections</h3>
<div class="paragraph">
<p>Naturally Hibernate also allows to persist collections.
These persistent collections can contain almost any other Hibernate type, including: basic types, custom types, components and references to other entities.
In this context, the distinction between value and reference semantics is very important.
An object in a collection might be handled with <em>value</em> semantics (its life cycle being fully depends on the collection owner),
or it might be a reference to another entity with its own life cycle.
In the latter case, only the <em>link</em> between the two objects is considered to be a state held by the collection.</p>
</div>
<div class="paragraph">
<p>The owner of the collection is always an entity, even if the collection is defined by an embeddable type.
Collections form one/many-to-many associations between types so there can be:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>value type collections</p>
</li>
<li>
<p>embeddable type collections</p>
</li>
<li>
<p>entity collections</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Hibernate uses its own collection implementations which are enriched with lazy-loading, caching or state change detection semantics.
For this reason, persistent collections must be declared as an interface type.
The actual interface might be <code>java.util.Collection</code>, <code>java.util.List</code>, <code>java.util.Set</code>, <code>java.util.Map</code>, <code>java.util.SortedSet</code>, <code>java.util.SortedMap</code> or even other object types (meaning you will have to write an implementation of <code>org.hibernate.usertype.UserCollectionType</code>).</p>
</div>
<div class="paragraph">
<p>As the following example demonstrates, it&#8217;s important to use the interface type and not the collection implementation, as declared in the entity mapping.</p>
</div>
<div id="collections-collection-proxy-example" class="exampleblock">
<div class="title">Example 164. Hibernate uses its own collection implementations</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    @ElementCollection
    private List&lt;String&gt; phones = new ArrayList&lt;&gt;();

    public List&lt;String&gt; getPhones() {
        return phones;
    }
}

Person person = entityManager.find( Person.class, 1L );
//Throws java.lang.ClassCastException: org.hibernate.collection.internal.PersistentBag cannot be cast to java.util.ArrayList
ArrayList&lt;String&gt; phones = (ArrayList&lt;String&gt;) person.getPhones();</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>It is important that collections be defined using the appropriate Java Collections Framework interface rather than a specific implementation.
From a theoretical perspective, this just follows good design principles.
From a practical perspective, Hibernate (like other persistence providers) will use their own collection implementations which conform to the Java Collections Framework interfaces.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The persistent collections injected by Hibernate behave like <code>ArrayList</code>, <code>HashSet</code>, <code>TreeSet</code>, <code>HashMap</code> or <code>TreeMap</code>, depending on the interface type.</p>
</div>
<div class="sect3">
<h4 id="collections-synopsis">Collections as a value type</h4>
<div class="paragraph">
<p>Value and embeddable type collections have a similar behavior as simple value types because they are automatically persisted when referenced by a persistent object and automatically deleted when unreferenced.
If a collection is passed from one persistent object to another, its elements might be moved from one table to another.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Two entities cannot share a reference to the same collection instance.
Collection-valued properties do not support null value semantics because Hibernate does not distinguish between a null collection reference and an empty collection.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="collections-value">Collections of value types</h4>
<div class="paragraph">
<p>Collections of value type include basic and embeddable types.
Collections cannot be nested, and, when used in collections, embeddable types are not allowed to define other collections.</p>
</div>
<div class="paragraph">
<p>For collections of value types, JPA 2.0 defines the <code>@ElementCollection</code> annotation.
The lifecycle of the value-type collection is entirely controlled by its owning entity.</p>
</div>
<div class="paragraph">
<p>Considering the previous example mapping, when clearing the phone collection, Hibernate deletes all the associated phones.
When adding a new element to the value type collection, Hibernate issues a new insert statement.</p>
</div>
<div id="collections-value-type-collection-lifecycle-example" class="exampleblock">
<div class="title">Example 165. Value type collection lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">person.getPhones().clear();
person.getPhones().add( "123-456-7890" );
person.getPhones().add( "456-000-1234" );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">DELETE FROM Person_phones WHERE   Person_id = 1

INSERT INTO Person_phones ( Person_id, phones )
VALUES ( 1, '123-456-7890' )

INSERT INTO Person_phones  (Person_id, phones)
VALUES  ( 1, '456-000-1234' )</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>If removing all elements or adding new ones is rather straightforward, removing a certain entry actually requires reconstructing the whole collection from scratch.</p>
</div>
<div id="collections-value-type-collection-remove-example" class="exampleblock">
<div class="title">Example 166. Removing collection elements</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">person.getPhones().remove( 0 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">DELETE FROM Person_phones WHERE Person_id = 1

INSERT INTO Person_phones ( Person_id, phones )
VALUES ( 1, '456-000-1234' )</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Depending on the number of elements, this behavior might not be efficient, if many elements need to be deleted and reinserted back into the database table.
A workaround is to use an <code>@OrderColumn</code>, which, although not as efficient as when using the actual link table primary key, might improve the efficiency of the remove operations.</p>
</div>
<div id="collections-value-type-collection-order-column-remove-example" class="exampleblock">
<div class="title">Example 167. Removing collection elements using the order column</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@ElementCollection
@OrderColumn(name = "order_id")
private List&lt;String&gt; phones = new ArrayList&lt;&gt;();

person.getPhones().remove( 0 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">DELETE FROM Person_phones
WHERE  Person_id = 1
       AND order_id = 1

UPDATE Person_phones
SET    phones = '456-000-1234'
WHERE  Person_id = 1
       AND order_id = 0</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The <code>@OrderColumn</code> column works best when removing from the tail of the collection, as it only requires a single delete statement.
Removing from the head or the middle of the collection requires deleting the extra elements and updating the remaining ones to preserve element order.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Embeddable type collections behave the same way as value type collections.
Adding embeddables to the collection triggers the associated insert statements and removing elements from the collection will generate delete statements.</p>
</div>
<div id="collections-embeddable-type-collection-lifecycle-example" class="exampleblock">
<div class="title">Example 168. Embeddable type collections</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    @ElementCollection
    private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();

    public List&lt;Phone&gt; getPhones() {
        return phones;
    }
}

@Embeddable
public static class Phone {

    private String type;

    @Column(name = "`number`")
    private String number;

    public Phone() {
    }

    public Phone(String type, String number) {
        this.type = type;
        this.number = number;
    }

    public String getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }
}

person.getPhones().add( new Phone( "landline", "028-234-9876" ) );
person.getPhones().add( new Phone( "mobile", "072-122-9876" ) );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Person_phones ( Person_id, number, type )
VALUES ( 1, '028-234-9876', 'landline' )

INSERT INTO Person_phones ( Person_id, number, type )
VALUES ( 1, '072-122-9876', 'mobile' )</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="collections-entity">Collections of entities</h4>
<div class="paragraph">
<p>If value type collections can only form a one-to-many association between an owner entity and multiple basic or embeddable types,
entity collections can represent both <a href="chapters/domain/associations.html#associations-one-to-many">@OneToMany</a> and <a href="chapters/domain/associations.html#associations-many-to-many">@ManyToMany</a> associations.</p>
</div>
<div class="paragraph">
<p>From a relational database perspective, associations are defined by the foreign key side (the child-side).
With value type collections, only the entity can control the association (the parent-side), but for a collection of entities, both sides of the association are managed by the persistence context.</p>
</div>
<div class="paragraph">
<p>For this reason, entity collections can be devised into two main categories: unidirectional and bidirectional associations.
Unidirectional associations are very similar to value type collections since only the parent side controls this relationship.
Bidirectional associations are more tricky since, even if sides need to be in-sync at all times, only one side is responsible for managing the association.
A bidirectional association has an <em>owning</em> side and an <em>inverse (mappedBy)</em> side.</p>
</div>
<div class="paragraph">
<p>Another way of categorizing entity collections is by the underlying collection type, and so we can have:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>bags</p>
</li>
<li>
<p>indexed lists</p>
</li>
<li>
<p>sets</p>
</li>
<li>
<p>sorted sets</p>
</li>
<li>
<p>maps</p>
</li>
<li>
<p>sorted maps</p>
</li>
<li>
<p>arrays</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In the following sections, we will go through all these collection types and discuss both unidirectional and bidirectional associations.</p>
</div>
</div>
<div class="sect3">
<h4 id="collections-bag">Bags</h4>
<div class="paragraph">
<p>Bags are unordered lists and we can have unidirectional bags or bidirectional ones.</p>
</div>
<div class="sect4">
<h5 id="collections-unidirectional-bag">Unidirectional bags</h5>
<div class="paragraph">
<p>The unidirectional bag is mapped using a single <code>@OneToMany</code> annotation on the parent side of the association.
Behind the scenes, Hibernate requires an association table to manage the parent-child relationship, as we can see in the following example:</p>
</div>
<div id="collections-unidirectional-bag-example" class="exampleblock">
<div class="title">Example 169. Unidirectional bag</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    @OneToMany(cascade = CascadeType.ALL)
    private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public List&lt;Phone&gt; getPhones() {
        return phones;
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    private Long id;

    private String type;

    @Column(name = "`number`")
    private String number;

    public Phone() {
    }

    public Phone(Long id, String type, String number) {
        this.id = id;
        this.type = type;
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE Person_Phone (
    Person_id BIGINT NOT NULL ,
    phones_id BIGINT NOT NULL
)

CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    type VARCHAR(255) ,
    PRIMARY KEY ( id )
)

ALTER TABLE Person_Phone
ADD CONSTRAINT UK_9uhc5itwc9h5gcng944pcaslf
UNIQUE (phones_id)

ALTER TABLE Person_Phone
ADD CONSTRAINT FKr38us2n8g5p9rj0b494sd3391
FOREIGN KEY (phones_id) REFERENCES Phone

ALTER TABLE Person_Phone
ADD CONSTRAINT FK2ex4e4p7w1cj310kg2woisjl2
FOREIGN KEY (Person_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Because both the parent and the child sides are entities, the persistence context manages each entity separately.
Cascades can propagate an entity state transition from a parent entity to its children.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>By marking the parent side with the <code>CascadeType.ALL</code> attribute, the unidirectional association lifecycle becomes very similar to that of a value type collection.</p>
</div>
<div id="collections-unidirectional-bag-lifecycle-example" class="exampleblock">
<div class="title">Example 170. Unidirectional bag lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = new Person( 1L );
person.getPhones().add( new Phone( 1L, "landline", "028-234-9876" ) );
person.getPhones().add( new Phone( 2L, "mobile", "072-122-9876" ) );
entityManager.persist( person );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Person ( id )
VALUES ( 1 )

INSERT INTO Phone ( number, type, id )
VALUES ( '028-234-9876', 'landline', 1 )

INSERT INTO Phone ( number, type, id )
VALUES ( '072-122-9876', 'mobile', 2 )

INSERT INTO Person_Phone ( Person_id, phones_id )
VALUES ( 1, 1 )

INSERT INTO Person_Phone ( Person_id, phones_id )
VALUES ( 1, 2 )</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In the example above, once the parent entity is persisted, the child entities are going to be persisted as well.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Just like value type collections, unidirectional bags are not as efficient when it comes to modifying the collection structure (removing or reshuffling elements).
Because the parent-side cannot uniquely identify each individual child, Hibernate might delete all child table rows associated with the parent entity and re-add them according to the current collection state.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect4">
<h5 id="collections-bidirectional-bag">Bidirectional bags</h5>
<div class="paragraph">
<p>The bidirectional bag is the most common type of entity collection.
The <code>@ManyToOne</code> side is the owning side of the bidirectional bag association, while the <code>@OneToMany</code> is the <em>inverse</em> side, being marked with the <code>mappedBy</code> attribute.</p>
</div>
<div id="collections-bidirectional-bag-example" class="exampleblock">
<div class="title">Example 171. Bidirectional bag</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public List&lt;Phone&gt; getPhones() {
        return phones;
    }

    public void addPhone(Phone phone) {
        phones.add( phone );
        phone.setPerson( this );
    }

    public void removePhone(Phone phone) {
        phones.remove( phone );
        phone.setPerson( null );
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    private Long id;

    private String type;

    @Column(name = "`number`", unique = true)
    @NaturalId
    private String number;

    @ManyToOne
    private Person person;

    public Phone() {
    }

    public Phone(Long id, String type, String number) {
        this.id = id;
        this.type = type;
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Phone phone = (Phone) o;
        return Objects.equals( number, phone.number );
    }

    @Override
    public int hashCode() {
        return Objects.hash( number );
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL, PRIMARY KEY (id)
)

CREATE TABLE Phone (
    id BIGINT NOT NULL,
    number VARCHAR(255),
    type VARCHAR(255),
    person_id BIGINT,
    PRIMARY KEY (id)
)

ALTER TABLE Phone
ADD CONSTRAINT UK_l329ab0g4c1t78onljnxmbnp6
UNIQUE (number)

ALTER TABLE Phone
ADD CONSTRAINT FKmw13yfsjypiiq0i1osdkaeqpg
FOREIGN KEy (person_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
<div id="collections-bidirectional-bag-lifecycle-example" class="exampleblock">
<div class="title">Example 172. Bidirectional bag lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">person.addPhone( new Phone( 1L, "landline", "028-234-9876" ) );
person.addPhone( new Phone( 2L, "mobile", "072-122-9876" ) );
entityManager.flush();
person.removePhone( person.getPhones().get( 0 ) );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Phone (number, person_id, type, id)
VALUES ( '028-234-9876', 1, 'landline', 1 )

INSERT INTO Phone (number, person_id, type, id)
VALUES ( '072-122-9876', 1, 'mobile', 2 )

UPDATE Phone
SET person_id = NULL, type = 'landline' where id = 1</code></pre>
</div>
</div>
</div>
</div>
<div id="collections-bidirectional-bag-orphan-removal-example" class="exampleblock">
<div class="title">Example 173. Bidirectional bag with orphan removal</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">DELETE FROM Phone WHERE id = 1</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When rerunning the previous example, the child will get removed because the parent-side propagates the removal upon disassociating the child entity reference.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="collections-list">Ordered Lists</h4>
<div class="paragraph">
<p>Although they use the <code>List</code> interface on the Java side, bags don&#8217;t retain element order.
To preserve the collection element order, there are two possibilities:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>@OrderBy</code></dt>
<dd>
<p>the collection is ordered upon retrieval using a child entity property</p>
</dd>
<dt class="hdlist1"><code>@OrderColumn</code></dt>
<dd>
<p>the collection uses a dedicated order column in the collection link table</p>
</dd>
</dl>
</div>
<div class="sect4">
<h5 id="collections-unidirectional-ordered-list">Unidirectional ordered lists</h5>
<div class="paragraph">
<p>When using the <code>@OrderBy</code> annotation, the mapping looks as follows:</p>
</div>
<div id="collections-unidirectional-ordered-list-order-by-example" class="exampleblock">
<div class="title">Example 174. Unidirectional <code>@OrderBy</code> list</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    @OneToMany(cascade = CascadeType.ALL)
    @OrderBy("number")
    private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public List&lt;Phone&gt; getPhones() {
        return phones;
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    private Long id;

    private String type;

    @Column(name = "`number`")
    private String number;

    public Phone() {
    }

    public Phone(Long id, String type, String number) {
        this.id = id;
        this.type = type;
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The database mapping is the same as with the <a href="#collections-unidirectional-bag">Unidirectional bags</a> example, so it won&#8217;t be repeated.
Upon fetching the collection, Hibernate generates the following select statement:</p>
</div>
<div id="collections-unidirectional-ordered-list-order-by-select-example" class="exampleblock">
<div class="title">Example 175. Unidirectional <code>@OrderBy</code> list select statement</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">SELECT
   phones0_.Person_id AS Person_i1_1_0_,
   phones0_.phones_id AS phones_i2_1_0_,
   unidirecti1_.id AS id1_2_1_,
   unidirecti1_."number" AS number2_2_1_,
   unidirecti1_.type AS type3_2_1_
FROM
   Person_Phone phones0_
INNER JOIN
   Phone unidirecti1_ ON phones0_.phones_id=unidirecti1_.id
WHERE
   phones0_.Person_id = 1
ORDER BY
   unidirecti1_."number"</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The child table column is used to order the list elements.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The <code>@OrderBy</code> annotation can take multiple entity properties, and each property can take an ordering direction too (e.g. <code>@OrderBy("name ASC, type DESC")</code>).</p>
</div>
<div class="paragraph">
<p>If no property is specified (e.g. <code>@OrderBy</code>), the primary key of the child entity table is used for ordering.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Another ordering option is to use the <code>@OrderColumn</code> annotation:</p>
</div>
<div id="collections-unidirectional-ordered-list-order-column-example" class="exampleblock">
<div class="title">Example 176. Unidirectional <code>@OrderColumn</code> list</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@OneToMany(cascade = CascadeType.ALL)
@OrderColumn(name = "order_id")
private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person_Phone (
    Person_id BIGINT NOT NULL ,
    phones_id BIGINT NOT NULL ,
    order_id INTEGER NOT NULL ,
    PRIMARY KEY ( Person_id, order_id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This time, the link table takes the <code>order_id</code> column and uses it to materialize the collection element order.
When fetching the list, the following select query is executed:</p>
</div>
<div id="collections-unidirectional-ordered-list-order-column-select-example" class="exampleblock">
<div class="title">Example 177. Unidirectional <code>@OrderColumn</code> list select statement</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">select
   phones0_.Person_id as Person_i1_1_0_,
   phones0_.phones_id as phones_i2_1_0_,
   phones0_.order_id as order_id3_0_,
   unidirecti1_.id as id1_2_1_,
   unidirecti1_.number as number2_2_1_,
   unidirecti1_.type as type3_2_1_
from
   Person_Phone phones0_
inner join
   Phone unidirecti1_
      on phones0_.phones_id=unidirecti1_.id
where
   phones0_.Person_id = 1</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>With the <code>order_id</code> column in place, Hibernate can order the list in-memory after it&#8217;s being fetched from the database.</p>
</div>
</div>
<div class="sect4">
<h5 id="collections-bidirectional-ordered-list">Bidirectional ordered lists</h5>
<div class="paragraph">
<p>The mapping is similar with the <a href="#collections-bidirectional-bag">Bidirectional bags</a> example, just that the parent side is going to be annotated with either <code>@OrderBy</code> or <code>@OrderColumn</code>.</p>
</div>
<div id="collections-bidirectional-ordered-list-order-by-example" class="exampleblock">
<div class="title">Example 178. Bidirectional <code>@OrderBy</code> list</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
@OrderBy("number")
private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Just like with the unidirectional <code>@OrderBy</code> list, the <code>number</code> column is used to order the statement on the SQL level.</p>
</div>
<div class="paragraph">
<p>When using the <code>@OrderColumn</code> annotation, the <code>order_id</code> column is going to be embedded in the child table:</p>
</div>
<div id="collections-bidirectional-ordered-list-order-column-example" class="exampleblock">
<div class="title">Example 179. Bidirectional <code>@OrderColumn</code> list</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
@OrderColumn(name = "order_id")
private List&lt;Phone&gt; phones = new ArrayList&lt;&gt;();</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    type VARCHAR(255) ,
    person_id BIGINT ,
    order_id INTEGER ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When fetching the collection, Hibernate will use the fetched ordered columns to sort the elements according to the <code>@OrderColumn</code> mapping.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="collections-set">Sets</h4>
<div class="paragraph">
<p>Sets are collections that don&#8217;t allow duplicate entries and Hibernate supports both the unordered <code>Set</code> and the natural-ordering <code>SortedSet</code>.</p>
</div>
<div class="sect4">
<h5 id="collections-unidirectional-set">Unidirectional sets</h5>
<div class="paragraph">
<p>The unidirectional set uses a link table to hold the parent-child associations and the entity mapping looks as follows:</p>
</div>
<div id="collections-unidirectional-set-example" class="exampleblock">
<div class="title">Example 180. Unidirectional set</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    @OneToMany(cascade = CascadeType.ALL)
    private Set&lt;Phone&gt; phones = new HashSet&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public Set&lt;Phone&gt; getPhones() {
        return phones;
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    private Long id;

    private String type;

    @NaturalId
    @Column(name = "`number`")
    private String number;

    public Phone() {
    }

    public Phone(Long id, String type, String number) {
        this.id = id;
        this.type = type;
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Phone phone = (Phone) o;
        return Objects.equals( number, phone.number );
    }

    @Override
    public int hashCode() {
        return Objects.hash( number );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The unidirectional set lifecycle is similar to that of the <a href="#collections-unidirectional-bag">Unidirectional bags</a>, so it can be omitted.
The only difference is that <code>Set</code> doesn&#8217;t allow duplicates, but this constraint is enforced by the Java object contract rather then the database mapping.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>When using sets, it&#8217;s very important to supply proper equals/hashCode implementations for child entities.
In the absence of a custom equals/hashCode implementation logic, Hibernate will use the default Java reference-based object equality which might render unexpected results when mixing detached and managed object instances.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect4">
<h5 id="collections-bidirectional-set">Bidirectional sets</h5>
<div class="paragraph">
<p>Just like bidirectional bags, the bidirectional set doesn&#8217;t use a link table, and the child table has a foreign key referencing the parent table primary key.
The lifecycle is just like with bidirectional bags except for the duplicates which are filtered out.</p>
</div>
<div id="collections-bidirectional-set-example" class="exampleblock">
<div class="title">Example 181. Bidirectional set</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    private Set&lt;Phone&gt; phones = new HashSet&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public Set&lt;Phone&gt; getPhones() {
        return phones;
    }

    public void addPhone(Phone phone) {
        phones.add( phone );
        phone.setPerson( this );
    }

    public void removePhone(Phone phone) {
        phones.remove( phone );
        phone.setPerson( null );
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    private Long id;

    private String type;

    @Column(name = "`number`", unique = true)
    @NaturalId
    private String number;

    @ManyToOne
    private Person person;

    public Phone() {
    }

    public Phone(Long id, String type, String number) {
        this.id = id;
        this.type = type;
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Phone phone = (Phone) o;
        return Objects.equals( number, phone.number );
    }

    @Override
    public int hashCode() {
        return Objects.hash( number );
    }
}</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="collections-sorted-set">Sorted sets</h4>
<div class="paragraph">
<p>For sorted sets, the entity mapping must use the <code>SortedSet</code> interface instead.
According to the <code>SortedSet</code> contract, all elements must implement the <code>Comparable</code> interface and therefore provide the sorting logic.</p>
</div>
<div class="sect4">
<h5 id="collections-unidirectional-sorted-set">Unidirectional sorted sets</h5>
<div class="paragraph">
<p>A <code>SortedSet</code> that relies on the natural sorting order given by the child element <code>Comparable</code> implementation logic must be annotated with the <code>@SortNatural</code> Hibernate annotation.</p>
</div>
<div id="collections-unidirectional-sorted-set-natural-comparator-example" class="exampleblock">
<div class="title">Example 182. Unidirectional natural sorted set</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    @OneToMany(cascade = CascadeType.ALL)
    @SortNatural
    private SortedSet&lt;Phone&gt; phones = new TreeSet&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public Set&lt;Phone&gt; getPhones() {
        return phones;
    }
}

@Entity(name = "Phone")
public static class Phone implements Comparable&lt;Phone&gt; {

    @Id
    private Long id;

    private String type;

    @NaturalId
    @Column(name = "`number`")
    private String number;

    public Phone() {
    }

    public Phone(Long id, String type, String number) {
        this.id = id;
        this.type = type;
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }

    @Override
    public int compareTo(Phone o) {
        return number.compareTo( o.getNumber() );
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Phone phone = (Phone) o;
        return Objects.equals( number, phone.number );
    }

    @Override
    public int hashCode() {
        return Objects.hash( number );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The lifecycle and the database mapping are identical to the <a href="#collections-unidirectional-bag">Unidirectional bags</a>, so they are intentionally omitted.</p>
</div>
<div class="paragraph">
<p>To provide a custom sorting logic, Hibernate also provides a <code>@SortComparator</code> annotation:</p>
</div>
<div id="collections-unidirectional-sorted-set-custom-comparator-example" class="exampleblock">
<div class="title">Example 183. Unidirectional custom comparator sorted set</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    @OneToMany(cascade = CascadeType.ALL)
    @SortComparator(ReverseComparator.class)
    private SortedSet&lt;Phone&gt; phones = new TreeSet&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public Set&lt;Phone&gt; getPhones() {
        return phones;
    }
}

public static class ReverseComparator implements Comparator&lt;Phone&gt; {
    @Override
    public int compare(Phone o1, Phone o2) {
        return o2.compareTo( o1 );
    }
}

@Entity(name = "Phone")
public static class Phone implements Comparable&lt;Phone&gt; {

    @Id
    private Long id;

    private String type;

    @NaturalId
    @Column(name = "`number`")
    private String number;

    public Phone() {
    }

    public Phone(Long id, String type, String number) {
        this.id = id;
        this.type = type;
        this.number = number;
    }

    public Long getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }

    @Override
    public int compareTo(Phone o) {
        return number.compareTo( o.getNumber() );
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }
        Phone phone = (Phone) o;
        return Objects.equals( number, phone.number );
    }

    @Override
    public int hashCode() {
        return Objects.hash( number );
    }
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="collections-bidirectional-sorted-set">Bidirectional sorted sets</h5>
<div class="paragraph">
<p>The <code>@SortNatural</code> and <code>@SortComparator</code> work the same for bidirectional sorted sets too:</p>
</div>
<div id="collections-bidirectional-sorted-set-example" class="exampleblock">
<div class="title">Example 184. Bidirectional natural sorted set</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
@SortNatural
private SortedSet&lt;Phone&gt; phones = new TreeSet&lt;&gt;();


@OneToMany(cascade = CascadeType.ALL)
@SortComparator(ReverseComparator.class)</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="collections-map">Maps</h4>
<div class="paragraph">
<p>A <code>java.util.Map</code> is ternary association because it required a parent entity a map key and a value.
An entity can either be a map key or a map value, depending on the mapping.
Hibernate allows using the following map keys:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>MapKeyColumn</code></dt>
<dd>
<p>for value type maps, the map key is a column in the link table that defines the grouping logic</p>
</dd>
<dt class="hdlist1"><code>MapKey</code></dt>
<dd>
<p>the map key is either the primary key or another property of the entity stored as a map entry value</p>
</dd>
<dt class="hdlist1"><code>MapKeyEnumerated</code></dt>
<dd>
<p>the map key is an <code>Enum</code> of the target child entity</p>
</dd>
<dt class="hdlist1"><code>MapKeyTemporal</code></dt>
<dd>
<p>the map key is a <code>Date</code> or a <code>Calendar</code> of the target child entity</p>
</dd>
<dt class="hdlist1"><code>MapKeyJoinColumn</code></dt>
<dd>
<p>the map key is an entity mapped as an association in the child entity that&#8217;s stored as a map entry key</p>
</dd>
</dl>
</div>
<div class="sect4">
<h5 id="collections-map-value-type">Value type maps</h5>
<div class="paragraph">
<p>A map of value type must use the <code>@ElementCollection</code> annotation, just like value type lists, bags or sets.</p>
</div>
<div id="collections-map-value-type-entity-key-example" class="exampleblock">
<div class="title">Example 185. Value type map with an entity as a map key</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">public enum PhoneType {
    LAND_LINE,
    MOBILE
}

@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    @Temporal(TemporalType.TIMESTAMP)
    @ElementCollection
    @CollectionTable(name = "phone_register")
    @Column(name = "since")
    @MapKeyJoinColumn(name = "phone_id", referencedColumnName = "id")
    private Map&lt;Phone, Date&gt; phoneRegister = new HashMap&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public Map&lt;Phone, Date&gt; getPhoneRegister() {
        return phoneRegister;
    }
}

@Embeddable
public static class Phone {

    private PhoneType type;

    @Column(name = "`number`")
    private String number;

    public Phone() {
    }

    public Phone(PhoneType type, String number) {
        this.type = type;
        this.number = number;
    }

    public PhoneType getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE phone_register (
    Person_id BIGINT NOT NULL ,
    since TIMESTAMP ,
    number VARCHAR(255) NOT NULL ,
    type INTEGER NOT NULL ,
    PRIMARY KEY ( Person_id, number, type )
)

ALTER TABLE phone_register
ADD CONSTRAINT FKrmcsa34hr68of2rq8qf526mlk
FOREIGN KEY (Person_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Adding entries to the map generates the following SQL statements:</p>
</div>
<div id="collections-map-value-type-entity-key-add-example" class="exampleblock">
<div class="title">Example 186. Adding value type map entries</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">person.getPhoneRegister().put(
    new Phone( PhoneType.LAND_LINE, "028-234-9876" ), new Date()
);
person.getPhoneRegister().put(
    new Phone( PhoneType.MOBILE, "072-122-9876" ), new Date()
);</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO phone_register (Person_id, number, type, since)
VALUES (1, '072-122-9876', 1, '2015-12-15 17:16:45.311')

INSERT INTO phone_register (Person_id, number, type, since)
VALUES (1, '028-234-9876', 0, '2015-12-15 17:16:45.311')</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="collections-map-unidirectional">Unidirectional maps</h5>
<div class="paragraph">
<p>A unidirectional map exposes a parent-child association from the parent-side only.
The following example shows a unidirectional map which also uses a <code>@MapKeyTemporal</code> annotation.
The map key is a timestamp and it&#8217;s taken from the child entity table.</p>
</div>
<div id="collections-map-unidirectional-example" class="exampleblock">
<div class="title">Example 187. Unidirectional Map</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">public enum PhoneType {
    LAND_LINE,
    MOBILE
}

@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(
            name = "phone_register",
            joinColumns = @JoinColumn(name = "phone_id"),
            inverseJoinColumns = @JoinColumn(name = "person_id"))
    @MapKey(name = "since")
    @MapKeyTemporal(TemporalType.TIMESTAMP)
    private Map&lt;Date, Phone&gt; phoneRegister = new HashMap&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public Map&lt;Date, Phone&gt; getPhoneRegister() {
        return phoneRegister;
    }

    public void addPhone(Phone phone) {
        phoneRegister.put( phone.getSince(), phone );
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    @GeneratedValue
    private Long id;

    private PhoneType type;

    @Column(name = "`number`")
    private String number;

    private Date since;

    public Phone() {
    }

    public Phone(PhoneType type, String number, Date since) {
        this.type = type;
        this.number = number;
        this.since = since;
    }

    public PhoneType getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }

    public Date getSince() {
        return since;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    since TIMESTAMP ,
    type INTEGER ,
    PRIMARY KEY ( id )
)

CREATE TABLE phone_register (
    phone_id BIGINT NOT NULL ,
    person_id BIGINT NOT NULL ,
    PRIMARY KEY ( phone_id, person_id )
)

ALTER TABLE phone_register
ADD CONSTRAINT FKc3jajlx41lw6clbygbw8wm65w
FOREIGN KEY (person_id) REFERENCES Phone

ALTER TABLE phone_register
ADD CONSTRAINT FK6npoomh1rp660o1b55py9ndw4
FOREIGN KEY (phone_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="collections-map-bidirectional">Bidirectional maps</h5>
<div class="paragraph">
<p>Like most bidirectional associations, this relationship is owned by the child-side while the parent is the inverse side and can propagate its own state transitions to the child entities.
In the following example, you can see that <code>@MapKeyEnumerated</code> was used so that the <code>Phone</code> enumeration becomes the map key.</p>
</div>
<div id="collections-map-bidirectional-example" class="exampleblock">
<div class="title">Example 188. Bidirectional Map</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
    @MapKey(name = "type")
    @MapKeyEnumerated
    private Map&lt;PhoneType, Phone&gt; phoneRegister = new HashMap&lt;&gt;();

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public Map&lt;PhoneType, Phone&gt; getPhoneRegister() {
        return phoneRegister;
    }

    public void addPhone(Phone phone) {
        phone.setPerson( this );
        phoneRegister.put( phone.getType(), phone );
    }
}

@Entity(name = "Phone")
public static class Phone {

    @Id
    @GeneratedValue
    private Long id;

    private PhoneType type;

    @Column(name = "`number`")
    private String number;

    private Date since;

    @ManyToOne
    private Person person;

    public Phone() {
    }

    public Phone(PhoneType type, String number, Date since) {
        this.type = type;
        this.number = number;
        this.since = since;
    }

    public PhoneType getType() {
        return type;
    }

    public String getNumber() {
        return number;
    }

    public Date getSince() {
        return since;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE Phone (
    id BIGINT NOT NULL ,
    number VARCHAR(255) ,
    since TIMESTAMP ,
    type INTEGER ,
    person_id BIGINT ,
    PRIMARY KEY ( id )
)

ALTER TABLE Phone
ADD CONSTRAINT FKmw13yfsjypiiq0i1osdkaeqpg
FOREIGN KEY (person_id) REFERENCES Person</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="collections-array">Arrays</h4>
<div class="paragraph">
<p>When it comes to arrays, there is quite a difference between Java arrays and relational database array types (e.g. VARRAY, ARRAY).
First, not all database systems implement the SQL-99 ARRAY type, and, for this reason, Hibernate doesn&#8217;t support native database array types.
Second, Java arrays are relevant for basic types only since storing multiple embeddables or entities should always be done using the Java Collection API.</p>
</div>
</div>
<div class="sect3">
<h4 id="collections-array-binary">Arrays as binary</h4>
<div class="paragraph">
<p>By default, Hibernate will choose a BINARY type, as supported by the current <code>Dialect</code>.</p>
</div>
<div id="collections-array-binary-example" class="exampleblock">
<div class="title">Example 189. Binary arrays</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;
    private String[] phones;

    public Person() {
    }

    public Person(Long id) {
        this.id = id;
    }

    public String[] getPhones() {
        return phones;
    }

    public void setPhones(String[] phones) {
        this.phones = phones;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Person (
    id BIGINT NOT NULL ,
    phones VARBINARY(255) ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="collections-as-basic">Collections as basic value type</h4>
<div class="paragraph">
<p>Notice how all the previous examples explicitly mark the collection attribute as either <code>ElementCollection</code>, <code>OneToMany</code> or <code>ManyToMany</code>.
Collections not marked as such require a custom Hibernate <code>Type</code> and the collection elements must be stored in a single database column.</p>
</div>
<div class="paragraph">
<p>This is sometimes beneficial. Consider a use-case such as a <code>VARCHAR</code> column that represents a delimited list/set of Strings.</p>
</div>
<div id="collections-comma-delimited-collection-example" class="exampleblock">
<div class="title">Example 190. Comma delimited collection</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    @Type(type = "comma_delimited_strings")
    private List&lt;String&gt; phones = new ArrayList&lt;&gt;();

    public List&lt;String&gt; getPhones() {
        return phones;
    }
}

public class CommaDelimitedStringsJavaTypeDescriptor extends AbstractTypeDescriptor&lt;List&gt; {

    public static final String DELIMITER = ",";

    public CommaDelimitedStringsJavaTypeDescriptor() {
        super(
            List.class,
            new MutableMutabilityPlan&lt;List&gt;() {
                @Override
                protected List deepCopyNotNull(List value) {
                    return new ArrayList( value );
                }
            }
        );
    }

    @Override
    public String toString(List value) {
        return ( (List&lt;String&gt;) value ).stream().collect( Collectors.joining( DELIMITER ) );
    }

    @Override
    public List fromString(String string) {
        List&lt;String&gt; values = new ArrayList&lt;&gt;();
        Collections.addAll( values, string.split( DELIMITER ) );
        return values;
    }

    @Override
    public &lt;X&gt; X unwrap(List value, Class&lt;X&gt; type, WrapperOptions options) {
        return (X) toString( value );
    }

    @Override
    public &lt;X&gt; List wrap(X value, WrapperOptions options) {
        return fromString( (String) value );
    }
}

public class CommaDelimitedStringsType extends AbstractSingleColumnStandardBasicType&lt;List&gt; {

    public CommaDelimitedStringsType() {
        super(
            VarcharTypeDescriptor.INSTANCE,
            new CommaDelimitedStringsJavaTypeDescriptor()
        );
    }

    @Override
    public String getName() {
        return "comma_delimited_strings";
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The developer can use the comma-delimited collection like any other collection we&#8217;ve discussed so far and Hibernate will take care of the type transformation part.
The collection itself behaves like any other basic value type, as its lifecycle is bound to its owner entity.</p>
</div>
<div id="collections-comma-delimited-collection-lifecycle-example" class="exampleblock">
<div class="title">Example 191. Comma delimited collection lifecycle</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">person.phones.add( "027-123-4567" );
person.phones.add( "028-234-9876" );
session.flush();
person.getPhones().remove( 0 );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Person ( phones, id )
VALUES ( '027-123-4567,028-234-9876', 1 )

UPDATE Person
SET    phones = '028-234-9876'
WHERE  id = 1</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>See the Hibernate Integrations Guide for more details on developing custom value type mappings.</p>
</div>
</div>
<div class="sect3">
<h4 id="collections-custom">Custom collection types</h4>
<div class="paragraph">
<p>If you wish to use other collection types than <code>List</code>, <code>Set</code> or <code>Map</code>, like <code>Queue</code> for instance,
you have to use a custom collection type, as illustrated by the following example:</p>
</div>
<div id="collections-custom-collection-mapping-example" class="exampleblock">
<div class="title">Example 192. Custom collection mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
public static class Person {

    @Id
    private Long id;

    @OneToMany(cascade = CascadeType.ALL)
    @CollectionType( type = "org.hibernate.userguide.collections.type.QueueType")
    private Collection&lt;Phone&gt; phones = new LinkedList&lt;&gt;();

    //Getters and setters are omitted for brevity

}

@Entity(name = "Phone")
public static class Phone implements Comparable&lt;Phone&gt; {

    @Id
    private Long id;

    private String type;

    @NaturalId
    @Column(name = "`number`")
    private String number;

    //Getters and setters are omitted for brevity

}

public class QueueType implements UserCollectionType {

    @Override
    public PersistentCollection instantiate(
            SharedSessionContractImplementor session,
            CollectionPersister persister) throws HibernateException {
        return new PersistentQueue( session );
    }

    @Override
    public PersistentCollection wrap(
            SharedSessionContractImplementor session,
            Object collection) {
        return new PersistentQueue( session, (List) collection );
    }

    @Override
    public Iterator getElementsIterator(Object collection) {
        return ( (Queue) collection ).iterator();
    }

    @Override
    public boolean contains(Object collection, Object entity) {
        return ( (Queue) collection ).contains( entity );
    }

    @Override
    public Object indexOf(Object collection, Object entity) {
        int i = ( (List) collection ).indexOf( entity );
        return ( i &lt; 0 ) ? null : i;
    }

    @Override
    public Object replaceElements(
            Object original,
            Object target,
            CollectionPersister persister,
            Object owner,
            Map copyCache,
            SharedSessionContractImplementor session)
            throws HibernateException {
        Queue result = (Queue) target;
        result.clear();
        result.addAll( (Queue) original );
        return result;
    }

    @Override
    public Object instantiate(int anticipatedSize) {
        return new LinkedList&lt;&gt;();
    }

}

public class PersistentQueue extends PersistentBag implements Queue {

    public PersistentQueue(SharedSessionContractImplementor session) {
        super( session );
    }

    public PersistentQueue(SharedSessionContractImplementor session, List list) {
        super( session, list );
    }

    @Override
    public boolean offer(Object o) {
        return add(o);
    }

    @Override
    public Object remove() {
        return poll();
    }

    @Override
    public Object poll() {
        int size = size();
        if(size &gt; 0) {
            Object first = get(0);
            remove( 0 );
            return first;
        }
        throw new NoSuchElementException();
    }

    @Override
    public Object element() {
        return peek();
    }

    @Override
    public Object peek() {
        return size() &gt; 0 ? get( 0 ) : null;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The reason why the <code>Queue</code> interface is not used for the entity attribute is because Hibernate only allows the following types:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>java.util.List</code></p>
</li>
<li>
<p><code>java.util.Set</code></p>
</li>
<li>
<p><code>java.util.Map</code></p>
</li>
<li>
<p><code>java.util.SortedSet</code></p>
</li>
<li>
<p><code>java.util.SortedMap</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>However, the custom collection type can still be customized as long as the base type is one of the aformentioned persistent types.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>This way, the <code>Phone</code> collection can be used as a <code>java.util.Queue</code>:</p>
</div>
<div id="collections-custom-collection-example" class="exampleblock">
<div class="title">Example 193. Custom collection example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = entityManager.find( Person.class, 1L );
Queue&lt;Phone&gt; phones = person.getPhones();
Phone head = phones.peek();
assertSame(head, phones.poll());
assertEquals( 1, phones.size() );</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="naturalid">Natural Ids</h3>
<div class="paragraph">
<p>Natural ids represent domain model unique identifiers that have a meaning in the real world too.
Even if a natural id does not make a good primary key (surrogate keys being usually preferred), it&#8217;s still useful to tell Hibernate about it.
As we will see later, Hibernate provides a dedicated, efficient API for loading an entity by its natural id much like it offers for loading by its identifier (PK).</p>
</div>
<div class="sect3">
<h4 id="naturalid-mapping">Natural Id Mapping</h4>
<div class="paragraph">
<p>Natural ids are defined in terms of one or more persistent attributes.</p>
</div>
<div class="exampleblock">
<div class="title">Example 194. Natural id using single basic attribute</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Company {

    @Id
    private Integer id;

    @NaturalId
    private String taxIdentifier;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="exampleblock">
<div class="title">Example 195. Natural id using single embedded attribute</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class PostalCarrier {

    @Id
    private Integer id;

    @NaturalId
    @Embedded
    private PostalCode postalCode;

    ...

}

@Embeddable
public class PostalCode {
    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="exampleblock">
<div class="title">Example 196. Natural id using multiple persistent attributes</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Course {

    @Id
    private Integer id;

    @NaturalId
    @ManyToOne
    private Department department;

    @NaturalId
    private String code;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="naturalid-api">Natural Id API</h4>
<div class="paragraph">
<p>As stated before, Hibernate provides an API for loading entities by their associate natural id.
This is represented by the <code>org.hibernate.NaturalIdLoadAccess</code> contract obtained via Session#byNaturalId.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>If the entity does not define a natural id, trying to load an entity by its natural id will throw an exception.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="exampleblock">
<div class="title">Example 197. Using NaturalIdLoadAccess</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session = ...;

Company company = session.byNaturalId( Company.class )
    .using( "taxIdentifier","abc-123-xyz" )
    .load();

PostalCarrier carrier = session.byNaturalId( PostalCarrier.class )
    .using( "postalCode",new PostalCode(... ) )
    .load();

Department department = ...;
Course course = session.byNaturalId( Course.class )
    .using( "department",department )
    .using( "code","101" )
    .load();</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>NaturalIdLoadAccess offers 2 distinct methods for obtaining the entity:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>load()</code></dt>
<dd>
<p>obtains a reference to the entity, making sure that the entity state is initialized</p>
</dd>
<dt class="hdlist1"><code>getReference()</code></dt>
<dd>
<p>obtains a reference to the entity. The state may or may not be initialized.
If the entity is already associated with the current running Session, that reference (loaded or not) is returned.
If the entity is not loaded in the current Session and the entity supports proxy generation, an uninitialized proxy is generated and returned, otherwise the entity is loaded from the database and returned.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p><code>NaturalIdLoadAccess</code> allows loading an entity by natural id and at the same time apply a pessimistic lock.
For additional details on locking, see the <a href="chapters/locking/Locking.html#locking">Locking</a> chapter.</p>
</div>
<div class="paragraph">
<p>We will discuss the last method available on NaturalIdLoadAccess ( <code>setSynchronizationEnabled()</code> ) in <a href="#naturalid-mutability-caching">Natural Id - Mutability and Caching</a>.</p>
</div>
<div class="paragraph">
<p>Because the <code>Company</code> and <code>PostalCarrier</code> entities define "simple" natural ids, we can load them as follows:</p>
</div>
<div class="exampleblock">
<div class="title">Example 198. Using SimpleNaturalIdLoadAccess</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session = ...;

Company company = session.bySimpleNaturalId( Company.class )
    .load( "abc-123-xyz" );

PostalCarrier carrier = session.bySimpleNaturalId( PostalCarrier.class )
    .load( new PostalCode(... ) );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Here we see the use of the <code>org.hibernate.SimpleNaturalIdLoadAccess</code> contract, obtained via <code>Session#bySimpleNaturalId().
`SimpleNaturalIdLoadAccess</code> is similar to <code>NaturalIdLoadAccess</code> except that it does not define the using method.
Instead, because these "simple" natural ids are defined based on just one attribute we can directly pass the corresponding value of that natural id attribute directly to the <code>load()</code> and <code>getReference()</code> methods.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>If the entity does not define a natural id, or if the natural id is not of a "simple" type, an exception will be thrown there.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="naturalid-mutability-caching">Natural Id - Mutability and Caching</h4>
<div class="paragraph">
<p>A natural id may be mutable or immutable. By default the <code>@NaturalId</code> annotation marks an immutable natural id attribute.
An immutable natural id is expected to never change its value.
If the value(s) of the natural id attribute(s) change, <code>@NaturalId(mutable=true)</code> should be used instead.</p>
</div>
<div class="exampleblock">
<div class="title">Example 199. Mutable natural id</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Person {

    @Id
    private Integer id;

    @NaturalId( mutable = true )
    private String ssn;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Within the Session, Hibernate maintains a mapping from natural id values to entity identifiers (PK) values.
If natural ids values changed, it is possible for this mapping to become out of date until a flush occurs.
To work around this condition, Hibernate will attempt to discover any such pending changes and adjust them when the <code>load()</code> or <code>getReference()</code> methods are executed.
To be clear: this is only pertinent for mutable natural ids.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>This <em>discovery and adjustment</em> have a performance impact.
If an application is certain that none of its mutable natural ids already associated with the Session have changed, it can disable that checking by calling <code>setSynchronizationEnabled(false)</code> (the default is true).
This will force Hibernate to circumvent the checking of mutable natural ids.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="exampleblock">
<div class="title">Example 200. Mutable natural id synchronization use-case</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;

Person person = session.bySimpleNaturalId( Person.class ).load( "123-45-6789" );
person.setSsn( "987-65-4321" );

...

// returns null!
person = session.bySimpleNaturalId( Person.class )
    .setSynchronizationEnabled( false )
    .load( "987-65-4321" );

// returns correctly!
person = session.bySimpleNaturalId( Person.class )
    .setSynchronizationEnabled( true )
    .load( "987-65-4321" );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Not only can this NaturalId-to-PK resolution be cached in the Session, but we can also have it cached in the second-level cache if second level caching is enabled.</p>
</div>
<div id="naturalid-caching" class="exampleblock">
<div class="title">Example 201. Natural id caching</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
@NaturalIdCache
public class Company {

    @Id
    private Integer id;

    @NaturalId
    private String taxIdentifier;

    ...
}</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="dynamic-model">Dynamic Model</h3>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>JPA only acknowledges the entity model mapping so, if you are concerned about JPA provider portability, it&#8217;s best to stick to the strict POJO model.
On the other hand, Hibernate can work with both POJO entities as well as with dynamic entity models.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="mapping-model-dynamic">Dynamic mapping models</h4>
<div class="paragraph">
<p>Persistent entities do not necessarily have to be represented as POJO/JavaBean classes.
Hibernate also supports dynamic models (using `Map`s of `Map`s at runtime).
With this approach, you do not write persistent classes, only mapping files.</p>
</div>
<div class="paragraph">
<p>A given entity has just one entity mode within a given SessionFactory.
This is a change from previous versions which allowed to define multiple entity modes for an entity and to select which to load.
Entity modes can now be mixed within a domain model; a dynamic entity might reference a POJO entity, and vice versa.</p>
</div>
<div class="exampleblock">
<div class="title">Example 202. Working with Dynamic Domain Models</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session s = openSession();
Transaction tx = s.beginTransaction();

// Create a customer entity
Map&lt;String, String&gt;david = new HashMap&lt;&gt;();
david.put( "name","David" );

// Create an organization entity
Map&lt;String, String&gt;foobar = new HashMap&lt;&gt;();
foobar.put( "name","Foobar Inc." );

// Link both
david.put( "organization",foobar );

// Save both
s.save( "Customer",david );
s.save( "Organization",foobar );

tx.commit();
s.close();</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The main advantage of dynamic models is quick turnaround time for prototyping without the need for entity class implementation.
The main down-fall is that you lose compile-time type checking and will likely deal with many exceptions at runtime.
However, as a result of the Hibernate mapping, the database schema can easily be normalized and sound, allowing to add a proper domain model implementation on top later on.</p>
</div>
<div class="paragraph">
<p>It is also interesting to note that dynamic models are great for certain integration use cases as well.
Envers, for example, makes extensive use of dynamic models to represent the historical data.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="entity-inheritance">Inheritance</h3>
<div class="paragraph">
<p>Although relational database systems don&#8217;t provide support for inheritance, Hibernate provides several strategies to leverage this object-oriented trait onto domain model entities:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">MappedSuperclass</dt>
<dd>
<p>Inheritance is implemented in domain model only without reflecting it in the database schema. See <a href="#entity-inheritance-mapped-superclass">MappedSuperclass</a>.</p>
</dd>
<dt class="hdlist1">Single table</dt>
<dd>
<p>The domain model class hierarchy is materialized into a single table which contains entities belonging to different class types. See <a href="#entity-inheritance-single-table">Single table</a>.</p>
</dd>
<dt class="hdlist1">Joined table</dt>
<dd>
<p>The base class and all the subclasses have their own database tables and fetching a subclass entity requires a join with the parent table as well. See <a href="#entity-inheritance-joined-table">Joined table</a>.</p>
</dd>
<dt class="hdlist1">Table per class</dt>
<dd>
<p>Each subclass has its own table containing both the subclass and the base class properties. See <a href="#entity-inheritance-table-per-class">Table per class</a>.</p>
</dd>
</dl>
</div>
<div class="sect3">
<h4 id="entity-inheritance-mapped-superclass">MappedSuperclass</h4>
<div class="paragraph">
<p>In the following domain model class hierarchy, a 'DebitAccount' and a 'CreditAccount' share the same 'Account' base class.</p>
</div>
<div class="paragraph">
<p><span class="image"><img src="images/domain/inheritance/inheritance_class_diagram.svg" alt="Inheritance class diagram"></span></p>
</div>
<div class="paragraph">
<p>When using <code>MappedSuperclass</code>, the inheritance is visible in the domain model only and each database table contains both the base class and the subclass properties.</p>
</div>
<div id="entity-inheritance-mapped-superclass-example" class="exampleblock">
<div class="title">Example 203. <code>@MappedSuperclass</code> inheritance</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@MappedSuperclass
public static class Account {

    @Id
    private Long id;

    private String owner;

    private BigDecimal balance;

    private BigDecimal interestRate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}

@Entity(name = "DebitAccount")
public static class DebitAccount extends Account {

    private BigDecimal overdraftFee;

    public BigDecimal getOverdraftFee() {
        return overdraftFee;
    }

    public void setOverdraftFee(BigDecimal overdraftFee) {
        this.overdraftFee = overdraftFee;
    }
}

@Entity(name = "CreditAccount")
public static class CreditAccount extends Account {

    private BigDecimal creditLimit;

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE DebitAccount (
    id BIGINT NOT NULL ,
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    overdraftFee NUMERIC(19, 2) ,
    PRIMARY KEY ( id )
)

CREATE TABLE CreditAccount (
    id BIGINT NOT NULL ,
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    creditLimit NUMERIC(19, 2) ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Because the <code>@MappedSuperclass</code> inheritance model is not mirrored at database level,
it&#8217;s not possible to use polymorphic queries (fetching subclasses by their base class).</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="entity-inheritance-single-table">Single table</h4>
<div class="paragraph">
<p>The single table inheritance strategy maps all subclasses to only one database table.
Each subclass declares its own persistent properties.
Version and id properties are assumed to be inherited from the root class.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>When omitting an explicit inheritance strategy (e.g. <code>@Inheritance</code>), JPA will choose the <code>SINGLE_TABLE</code> strategy by default.</p>
</div>
</td>
</tr>
</table>
</div>
<div id="entity-inheritance-single-table-example" class="exampleblock">
<div class="title">Example 204. Single Table inheritance</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Account")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public static class Account {

    @Id
    private Long id;

    private String owner;

    private BigDecimal balance;

    private BigDecimal interestRate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}

@Entity(name = "DebitAccount")
public static class DebitAccount extends Account {

    private BigDecimal overdraftFee;

    public BigDecimal getOverdraftFee() {
        return overdraftFee;
    }

    public void setOverdraftFee(BigDecimal overdraftFee) {
        this.overdraftFee = overdraftFee;
    }
}

@Entity(name = "CreditAccount")
public static class CreditAccount extends Account {

    private BigDecimal creditLimit;

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Account (
    DTYPE VARCHAR(31) NOT NULL ,
    id BIGINT NOT NULL ,
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    overdraftFee NUMERIC(19, 2) ,
    creditLimit NUMERIC(19, 2) ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Each subclass in a hierarchy must define a unique discriminator value, which is used to differentiate between rows belonging to separate subclass types.
If this is not specified, the <code>DTYPE</code> column is used as a discriminator, storing the associated subclass name.</p>
</div>
<div id="entity-inheritance-single-table-persist-example" class="exampleblock">
<div class="title">Example 205. Single Table inheritance discriminator column</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">DebitAccount debitAccount = new DebitAccount();
debitAccount.setId( 1L );
debitAccount.setOwner( "John Doe" );
debitAccount.setBalance( BigDecimal.valueOf( 100 ) );
debitAccount.setInterestRate( BigDecimal.valueOf( 1.5d ) );
debitAccount.setOverdraftFee( BigDecimal.valueOf( 25 ) );

CreditAccount creditAccount = new CreditAccount();
creditAccount.setId( 2L );
creditAccount.setOwner( "John Doe" );
creditAccount.setBalance( BigDecimal.valueOf( 1000 ) );
creditAccount.setInterestRate( BigDecimal.valueOf( 1.9d ) );
creditAccount.setCreditLimit( BigDecimal.valueOf( 5000 ) );

entityManager.persist( debitAccount );
entityManager.persist( creditAccount );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Account (balance, interestRate, owner, overdraftFee, DTYPE, id)
VALUES (100, 1.5, 'John Doe', 25, 'DebitAccount', 1)

INSERT INTO Account (balance, interestRate, owner, creditLimit, DTYPE, id)
VALUES (1000, 1.9, 'John Doe', 5000, 'CreditAccount', 2)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When using polymorphic queries, only a single table is required to be scanned to fetch all associated subclass instances.</p>
</div>
<div id="entity-inheritance-single-table-query-example" class="exampleblock">
<div class="title">Example 206. Single Table polymorphic query</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">List&lt;Account&gt; accounts = entityManager
    .createQuery( "select a from Account a" )
    .getResultList();</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">SELECT  singletabl0_.id AS id2_0_ ,
        singletabl0_.balance AS balance3_0_ ,
        singletabl0_.interestRate AS interest4_0_ ,
        singletabl0_.owner AS owner5_0_ ,
        singletabl0_.overdraftFee AS overdraf6_0_ ,
        singletabl0_.creditLimit AS creditLi7_0_ ,
        singletabl0_.DTYPE AS DTYPE1_0_
FROM    Account singletabl0_</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Among all other inheritance alternatives, the single table strategy performs the best since it requires access to one table only.
Because all subclass columns are stored in a single table, it&#8217;s not possible to use NOT NULL constraints anymore, so integrity checks must be moved either into the data access layer or enforced through <code>CHECK</code> or <code>TRIGGER</code> constraints.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect4">
<h5 id="entity-inheritance-discriminator">Discriminator</h5>
<div class="paragraph">
<p>The discriminator column contains marker values that tell the persistence layer what subclass to instantiate for a particular row.
Hibernate Core supports the following restricted set of types as discriminator column: <code>String</code>, <code>char</code>, <code>int</code>, <code>byte</code>, <code>short</code>, <code>boolean</code>(including <code>yes_no</code>, <code>true_false</code>).</p>
</div>
<div class="paragraph">
<p>Use the <code>@DiscriminatorColumn</code> to define the discriminator column as well as the discriminator type.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The enum <code>DiscriminatorType</code> used in <code>javax.persistence.DiscriminatorColumn</code> only contains the values <code>STRING</code>, <code>CHAR</code> and <code>INTEGER</code> which means that not all Hibernate supported types are available via the <code>@DiscriminatorColumn</code> annotation.
You can also use <code>@DiscriminatorFormula</code> to express in SQL a virtual discriminator column.
This is particularly useful when the discriminator value can be extracted from one or more columns of the table.
Both <code>@DiscriminatorColumn</code> and <code>@DiscriminatorFormula</code> are to be set on the root entity (once per persisted hierarchy).</p>
</div>
<div class="paragraph">
<p><code>@org.hibernate.annotations.DiscriminatorOptions</code> allows to optionally specify Hibernate specific discriminator options which are not standardized in JPA.
The available options are <code>force</code> and <code>insert</code>.</p>
</div>
<div class="paragraph">
<p>The <code>force</code> attribute is useful if the table contains rows with <em>extra</em> discriminator values that are not mapped to a persistent class.
This could for example occur when working with a legacy database.
If <code>force</code> is set to true Hibernate will specify the allowed discriminator values in the SELECT query, even when retrieving all instances of the root class.</p>
</div>
<div class="paragraph">
<p>The second option, <code>insert</code>, tells Hibernate whether or not to include the discriminator column in SQL INSERTs.
Usually, the column should be part of the INSERT statement, but if your discriminator column is also part of a mapped composite identifier you have to set this option to false.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>There used to be <code>@org.hibernate.annotations.ForceDiscriminator</code> annotation which was deprecated in version 3.6 and later removed. Use <code>@DiscriminatorOptions</code> instead.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect5">
<h6 id="entity-inheritance-discriminator-formula">Discriminator formula</h6>
<div class="paragraph">
<p>Assuming a legacy database schema where the discriminator is based on inspecting a certain column,
we can take advantage of the Hibernate specific <code>@DiscriminatorFormula</code> annotation and map the inheritance model as follows:</p>
</div>
<div id="entity-inheritance-single-table-discriminator-formula-example" class="exampleblock">
<div class="title">Example 207. Single Table discriminator formula</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Account")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorFormula(
    "case when debitKey is not null " +
    "then 'Debit' " +
    "else ( " +
    "   case when creditKey is not null " +
    "   then 'Credit' " +
    "   else 'Unknown' " +
    "   end ) " +
    "end "
)
public static class Account {

    @Id
    private Long id;

    private String owner;

    private BigDecimal balance;

    private BigDecimal interestRate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}

@Entity(name = "DebitAccount")
@DiscriminatorValue(value = "Debit")
public static class DebitAccount extends Account {

    private String debitKey;

    private BigDecimal overdraftFee;

    private DebitAccount() {
    }

    public DebitAccount(String debitKey) {
        this.debitKey = debitKey;
    }

    public String getDebitKey() {
        return debitKey;
    }

    public BigDecimal getOverdraftFee() {
        return overdraftFee;
    }

    public void setOverdraftFee(BigDecimal overdraftFee) {
        this.overdraftFee = overdraftFee;
    }
}

@Entity(name = "CreditAccount")
@DiscriminatorValue(value = "Credit")
public static class CreditAccount extends Account {

    private String creditKey;

    private BigDecimal creditLimit;

    private CreditAccount() {
    }

    public CreditAccount(String creditKey) {
        this.creditKey = creditKey;
    }

    public String getCreditKey() {
        return creditKey;
    }

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Account (
    id int8 NOT NULL ,
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    debitKey VARCHAR(255) ,
    overdraftFee NUMERIC(19, 2) ,
    creditKey VARCHAR(255) ,
    creditLimit NUMERIC(19, 2) ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>@DiscriminatorFormula</code> defines a custom SQL clause that can be used to identify a certain subclass type.
The <code>@DiscriminatorValue</code> defines the mapping between the result of the <code>@DiscriminatorFormula</code> and the inheritance subclass type.</p>
</div>
</div>
<div class="sect5">
<h6 id="entity-inheritance-discriminator-implicit">Implicit discriminator values</h6>
<div class="paragraph">
<p>Aside from the usual discriminator values assigned to each individual subclass type, the <code>@DiscriminatorValue</code> can take two additional values:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>null</code></dt>
<dd>
<p>If the underlying discriminator column is null, the <code>null</code> discriminator mapping is going to be used.</p>
</dd>
<dt class="hdlist1"><code>not null</code></dt>
<dd>
<p>If the underlying discriminator column has a not-null value that is not explicitly mapped to any entity, the <code>not-null</code> discriminator mapping used.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>To understand how these two values work, consider the following entity mapping:</p>
</div>
<div id="entity-inheritance-single-table-discriminator-value-example" class="exampleblock">
<div class="title">Example 208. @DiscriminatorValue <code>null</code> and <code>not-null</code> entity mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Account")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorValue( "null" )
public static class Account {

    @Id
    private Long id;

    private String owner;

    private BigDecimal balance;

    private BigDecimal interestRate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}

@Entity(name = "DebitAccount")
@DiscriminatorValue( "Debit" )
public static class DebitAccount extends Account {

    private BigDecimal overdraftFee;

    public BigDecimal getOverdraftFee() {
        return overdraftFee;
    }

    public void setOverdraftFee(BigDecimal overdraftFee) {
        this.overdraftFee = overdraftFee;
    }
}

@Entity(name = "CreditAccount")
@DiscriminatorValue( "Credit" )
public static class CreditAccount extends Account {

    private BigDecimal creditLimit;

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}

@Entity(name = "OtherAccount")
@DiscriminatorValue( "not null" )
public static class OtherAccount extends Account {

    private boolean active;

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>Account</code> class has a <code>@DiscriminatorValue( "null" )</code> mapping, meaning that any <code>account</code> row which does not contain any discriminator value will be mapped to an <code>Account</code> base class entity.
The <code>DebitAccount</code> and <code>CreditAccount</code> entities use explicit discriminator values.
The <code>OtherAccount</code> entity is used as a generic account type because it maps any database row whose discriminator column is not explicitly assigned to any other entity in the current inheritance tree.</p>
</div>
<div class="paragraph">
<p>To visualize how it works, consider the following example:</p>
</div>
<div id="entity-inheritance-single-table-discriminator-value-persist-example" class="exampleblock">
<div class="title">Example 209. @DiscriminatorValue <code>null</code> and <code>not-null</code> entity persistence</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">DebitAccount debitAccount = new DebitAccount();
debitAccount.setId( 1L );
debitAccount.setOwner( "John Doe" );
debitAccount.setBalance( BigDecimal.valueOf( 100 ) );
debitAccount.setInterestRate( BigDecimal.valueOf( 1.5d ) );
debitAccount.setOverdraftFee( BigDecimal.valueOf( 25 ) );

CreditAccount creditAccount = new CreditAccount();
creditAccount.setId( 2L );
creditAccount.setOwner( "John Doe" );
creditAccount.setBalance( BigDecimal.valueOf( 1000 ) );
creditAccount.setInterestRate( BigDecimal.valueOf( 1.9d ) );
creditAccount.setCreditLimit( BigDecimal.valueOf( 5000 ) );

Account account = new Account();
account.setId( 3L );
account.setOwner( "John Doe" );
account.setBalance( BigDecimal.valueOf( 1000 ) );
account.setInterestRate( BigDecimal.valueOf( 1.9d ) );

entityManager.persist( debitAccount );
entityManager.persist( creditAccount );
entityManager.persist( account );

entityManager.unwrap( Session.class ).doWork( connection -&gt; {
    try(Statement statement = connection.createStatement()) {
        statement.executeUpdate(
            "insert into Account (DTYPE, active, balance, interestRate, owner, id) " +
            "values ('Other', true, 25, 0.5, 'Vlad', 4)"
        );
    }
} );

Map&lt;Long, Account&gt; accounts = entityManager.createQuery(
    "select a from Account a", Account.class )
.getResultList()
.stream()
.collect( Collectors.toMap( Account::getId, Function.identity()));

assertEquals(4, accounts.size());
assertEquals( DebitAccount.class, accounts.get( 1L ).getClass() );
assertEquals( CreditAccount.class, accounts.get( 2L ).getClass() );
assertEquals( Account.class, accounts.get( 3L ).getClass() );
assertEquals( OtherAccount.class, accounts.get( 4L ).getClass() );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">INSERT INTO Account (balance, interestRate, owner, overdraftFee, DTYPE, id)
VALUES (100, 1.5, 'John Doe', 25, 'Debit', 1)

INSERT INTO Account (balance, interestRate, owner, overdraftFee, DTYPE, id)
VALUES (1000, 1.9, 'John Doe', 5000, 'Credit', 2)

INSERT INTO Account (balance, interestRate, owner, id)
VALUES (1000, 1.9, 'John Doe', 3)

INSERT INTO Account (DTYPE, active, balance, interestRate, owner, id)
VALUES ('Other', true, 25, 0.5, 'Vlad', 4)

SELECT a.id as id2_0_,
       a.balance as balance3_0_,
       a.interestRate as interest4_0_,
       a.owner as owner5_0_,
       a.overdraftFee as overdraf6_0_,
       a.creditLimit as creditLi7_0_,
       a.active as active8_0_,
       a.DTYPE as DTYPE1_0_
FROM   Account a</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see, the <code>Account</code> entity row has a value of <code>NULL</code> in the <code>DTYPE</code> discriminator column,
while the <code>OtherAccount</code> entity was saved with a <code>DTYPE</code> column value of <code>other</code> which has not explicit mapping.</p>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="entity-inheritance-joined-table">Joined table</h4>
<div class="paragraph">
<p>Each subclass can also be mapped to its own table.
This is also called <em>table-per-subclass</em> mapping strategy.
An inherited state is retrieved by joining with the table of the superclass.</p>
</div>
<div class="paragraph">
<p>A discriminator column is not required for this mapping strategy.
Each subclass must, however, declare a table column holding the object identifier.</p>
</div>
<div id="entity-inheritance-joined-table-example" class="exampleblock">
<div class="title">Example 210. Join Table</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Account")
@Inheritance(strategy = InheritanceType.JOINED)
public static class Account {

    @Id
    private Long id;

    private String owner;

    private BigDecimal balance;

    private BigDecimal interestRate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}

@Entity(name = "DebitAccount")
public static class DebitAccount extends Account {

    private BigDecimal overdraftFee;

    public BigDecimal getOverdraftFee() {
        return overdraftFee;
    }

    public void setOverdraftFee(BigDecimal overdraftFee) {
        this.overdraftFee = overdraftFee;
    }
}

@Entity(name = "CreditAccount")
public static class CreditAccount extends Account {

    private BigDecimal creditLimit;

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Account (
    id BIGINT NOT NULL ,
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    PRIMARY KEY ( id )
)

CREATE TABLE CreditAccount (
    creditLimit NUMERIC(19, 2) ,
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

CREATE TABLE DebitAccount (
    overdraftFee NUMERIC(19, 2) ,
    id BIGINT NOT NULL ,
    PRIMARY KEY ( id )
)

ALTER TABLE CreditAccount
ADD CONSTRAINT FKihw8h3j1k0w31cnyu7jcl7n7n
FOREIGN KEY (id) REFERENCES Account

ALTER TABLE DebitAccount
ADD CONSTRAINT FKia914478noepymc468kiaivqm
FOREIGN KEY (id) REFERENCES Account</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The primary key of this table is also a foreign key to the superclass table and described by the <code>@PrimaryKeyJoinColumns</code>.</p>
</div>
<div class="paragraph">
<p>The table name still defaults to the non-qualified class name.
Also, if <code>@PrimaryKeyJoinColumn</code> is not set, the primary key / foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.</p>
</div>
</td>
</tr>
</table>
</div>
<div id="entity-inheritance-joined-table-primary-key-join-column-example" class="exampleblock">
<div class="title">Example 211. Join Table with <code>@PrimaryKeyJoinColumn</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Account")
@Inheritance(strategy = InheritanceType.JOINED)
public static class Account {

    @Id
    private Long id;

    private String owner;

    private BigDecimal balance;

    private BigDecimal interestRate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}

@Entity(name = "DebitAccount")
@PrimaryKeyJoinColumn(name = "account_id")
public static class DebitAccount extends Account {

    private BigDecimal overdraftFee;

    public BigDecimal getOverdraftFee() {
        return overdraftFee;
    }

    public void setOverdraftFee(BigDecimal overdraftFee) {
        this.overdraftFee = overdraftFee;
    }
}

@Entity(name = "CreditAccount")
@PrimaryKeyJoinColumn(name = "account_id")
public static class CreditAccount extends Account {

    private BigDecimal creditLimit;

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE CreditAccount (
    creditLimit NUMERIC(19, 2) ,
    account_id BIGINT NOT NULL ,
    PRIMARY KEY ( account_id )
)

CREATE TABLE DebitAccount (
    overdraftFee NUMERIC(19, 2) ,
    account_id BIGINT NOT NULL ,
    PRIMARY KEY ( account_id )
)

ALTER TABLE CreditAccount
ADD CONSTRAINT FK8ulmk1wgs5x7igo370jt0q005
FOREIGN KEY (account_id) REFERENCES Account

ALTER TABLE DebitAccount
ADD CONSTRAINT FK7wjufa570onoidv4omkkru06j
FOREIGN KEY (account_id) REFERENCES Account</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When using polymorphic queries, the base class table must be joined with all subclass tables to fetch every associated subclass instance.</p>
</div>
<div id="entity-inheritance-joined-table-query-example" class="exampleblock">
<div class="title">Example 212. Join Table polymorphic query</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">List&lt;Account&gt; accounts = entityManager
    .createQuery( "select a from Account a" )
    .getResultList();</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">SELECT jointablet0_.id AS id1_0_ ,
       jointablet0_.balance AS balance2_0_ ,
       jointablet0_.interestRate AS interest3_0_ ,
       jointablet0_.owner AS owner4_0_ ,
       jointablet0_1_.overdraftFee AS overdraf1_2_ ,
       jointablet0_2_.creditLimit AS creditLi1_1_ ,
       CASE WHEN jointablet0_1_.id IS NOT NULL THEN 1
            WHEN jointablet0_2_.id IS NOT NULL THEN 2
            WHEN jointablet0_.id IS NOT NULL THEN 0
       END AS clazz_
FROM   Account jointablet0_
       LEFT OUTER JOIN DebitAccount jointablet0_1_ ON jointablet0_.id = jointablet0_1_.id
       LEFT OUTER JOIN CreditAccount jointablet0_2_ ON jointablet0_.id = jointablet0_2_.id</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The joined table inheritance polymorphic queries can use several JOINS which might affect performance when fetching a large number of entities.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="entity-inheritance-table-per-class">Table per class</h4>
<div class="paragraph">
<p>A third option is to map only the concrete classes of an inheritance hierarchy to tables.
This is called the table-per-concrete-class strategy.
Each table defines all persistent states of the class, including the inherited state.</p>
</div>
<div class="paragraph">
<p>In Hibernate, it is not necessary to explicitly map such inheritance hierarchies.
You can map each class as a separate entity root.
However, if you wish use polymorphic associations (e.g. an association to the superclass of your hierarchy), you need to use the union subclass mapping.</p>
</div>
<div id="entity-inheritance-table-per-class-example" class="exampleblock">
<div class="title">Example 213. Table per class</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Account")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public static class Account {

    @Id
    private Long id;

    private String owner;

    private BigDecimal balance;

    private BigDecimal interestRate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}

@Entity(name = "DebitAccount")
public static class DebitAccount extends Account {

    private BigDecimal overdraftFee;

    public BigDecimal getOverdraftFee() {
        return overdraftFee;
    }

    public void setOverdraftFee(BigDecimal overdraftFee) {
        this.overdraftFee = overdraftFee;
    }
}

@Entity(name = "CreditAccount")
public static class CreditAccount extends Account {

    private BigDecimal creditLimit;

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">CREATE TABLE Account (
    id BIGINT NOT NULL ,
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    PRIMARY KEY ( id )
)

CREATE TABLE CreditAccount (
    id BIGINT NOT NULL ,
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    creditLimit NUMERIC(19, 2) ,
    PRIMARY KEY ( id )
)

CREATE TABLE DebitAccount (
    id BIGINT NOT NULL ,
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    overdraftFee NUMERIC(19, 2) ,
    PRIMARY KEY ( id )
)</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When using polymorphic queries, a UNION is required to fetch the base class table along with all subclass tables as well.</p>
</div>
<div class="exampleblock">
<div class="title">Example 214. Table per class polymorphic query</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">List&lt;Account&gt; accounts = entityManager
    .createQuery( "select a from Account a" )
    .getResultList();</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-sql" data-lang="sql">SELECT tablepercl0_.id AS id1_0_ ,
       tablepercl0_.balance AS balance2_0_ ,
       tablepercl0_.interestRate AS interest3_0_ ,
       tablepercl0_.owner AS owner4_0_ ,
       tablepercl0_.overdraftFee AS overdraf1_2_ ,
       tablepercl0_.creditLimit AS creditLi1_1_ ,
       tablepercl0_.clazz_ AS clazz_
FROM (
    SELECT    id ,
             balance ,
             interestRate ,
             owner ,
             CAST(NULL AS INT) AS overdraftFee ,
             CAST(NULL AS INT) AS creditLimit ,
             0 AS clazz_
    FROM     Account
    UNION ALL
    SELECT   id ,
             balance ,
             interestRate ,
             owner ,
             overdraftFee ,
             CAST(NULL AS INT) AS creditLimit ,
             1 AS clazz_
    FROM     DebitAccount
    UNION ALL
    SELECT   id ,
             balance ,
             interestRate ,
             owner ,
             CAST(NULL AS INT) AS overdraftFee ,
             creditLimit ,
             2 AS clazz_
    FROM     CreditAccount
) tablepercl0_</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Polymorphic queries require multiple UNION queries, so be aware of the performance implications of a large class hierarchy.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="entity-immutability">Immutability</h3>
<div class="paragraph">
<p>Immutability can be specified for both entities and collections.</p>
</div>
<div class="sect3">
<h4 id="_entity_immutability">Entity immutability</h4>
<div class="paragraph">
<p>If a specific entity is immutable, it is good practice to mark it with the <code>@Immutable</code> annotation.</p>
</div>
<div class="exampleblock">
<div class="title">Example 215. Immutable entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Event")
@Immutable
public static class Event {

    @Id
    private Long id;

    private Date createdOn;

    private String message;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Internally, Hibernate is going to perform several optimizations, such as:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>reducing memory footprint since there is no need to retain the dehydrated state for the dirty checking mechanism</p>
</li>
<li>
<p>speeding-up the Persistence Context flushing phase since immutable entities can skip the dirty checking process</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Considering the following entity is persisted in the database:</p>
</div>
<div class="exampleblock">
<div class="title">Example 216. Persisting an immutable entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Event event = new Event();
    event.setId( 1L );
    event.setCreatedOn( new Date( ) );
    event.setMessage( "Hibernate User Guide rocks!" );

    entityManager.persist( event );
} );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When loading the entity and trying to change its state,
Hibernate will skip any modification, therefore no SQL <code>UPDATE</code> statement is executed.</p>
</div>
<div class="exampleblock">
<div class="title">Example 217. The immutable entity ignores any update</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Event event = entityManager.find( Event.class, 1L );
    log.info( "Change event message" );
    event.setMessage( "Hibernate User Guide" );
} );
doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Event event = entityManager.find( Event.class, 1L );
    assertEquals("Hibernate User Guide rocks!", event.getMessage());
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT e.id AS id1_0_0_,
       e.createdOn AS createdO2_0_0_,
       e.message AS message3_0_0_
FROM   event e
WHERE  e.id = 1

-- Change event message

SELECT e.id AS id1_0_0_,
       e.createdOn AS createdO2_0_0_,
       e.message AS message3_0_0_
FROM   event e
WHERE  e.id = 1</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_collection_immutability">Collection immutability</h4>
<div class="paragraph">
<p>Just like entities, collections can also be marked with the <code>@Immutable</code> annotation.</p>
</div>
<div class="paragraph">
<p>Considering the following entity mappings:</p>
</div>
<div class="exampleblock">
<div class="title">Example 218. Immutable collection</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">@Entity(name = "Batch")
public static class Batch {

    @Id
    private Long id;

    private String name;

    @OneToMany(cascade = CascadeType.ALL)
    @Immutable
    private List&lt;Event&gt; events = new ArrayList&lt;&gt;( );

    //Getters and setters are omitted for brevity

}

@Entity(name = "Event")
@Immutable
public static class Event {

    @Id
    private Long id;

    private Date createdOn;

    private String message;

    //Getters and setters are omitted for brevity

}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This time, not only the <code>Event</code> entity is immutable, but the <code>Event</code> collection stored by the <code>Batch</code> parent entity.
Once the immutable collection is created, it can never be modified.</p>
</div>
<div class="exampleblock">
<div class="title">Example 219. Persisting an immutable collection</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Batch batch = new Batch();
    batch.setId( 1L );
    batch.setName( "Change request" );

    Event event1 = new Event();
    event1.setId( 1L );
    event1.setCreatedOn( new Date( ) );
    event1.setMessage( "Update Hibernate User Guide" );

    Event event2 = new Event();
    event2.setId( 2L );
    event2.setCreatedOn( new Date( ) );
    event2.setMessage( "Update Hibernate Getting Started Guide" );

    batch.getEvents().add( event1 );
    batch.getEvents().add( event2 );

    entityManager.persist( batch );
} );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The <code>Batch</code> entity is mutable. Only the <code>events</code> collection is immutable.</p>
</div>
<div class="paragraph">
<p>For instance, we can still modify the entity name:</p>
</div>
<div class="exampleblock">
<div class="title">Example 220. Changing the mutable entity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">doInJPA( this::entityManagerFactory, entityManager -&gt; {
    Batch batch = entityManager.find( Batch.class, 1L );
    log.info( "Change batch name" );
    batch.setName( "Proposed change request" );
} );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">SELECT b.id AS id1_0_0_,
       b.name AS name2_0_0_
FROM   Batch b
WHERE  b.id = 1

-- Change batch name

UPDATE batch
SET    name = 'Proposed change request'
WHERE  id = 1</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>However, when trying to modify the <code>events</code> collection:</p>
</div>
<div class="exampleblock">
<div class="title">Example 221. Immutable collections cannot be modified</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-JAVA" data-lang="JAVA">try {
    doInJPA( this::entityManagerFactory, entityManager -&gt; {
        Batch batch = entityManager.find( Batch.class, 1L );
        batch.getEvents().clear();
    } );
}
catch ( Exception e ) {
    log.error( "Immutable collections cannot be modified" );
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">Unresolved directive in immutability.adoc - include::extras/immutability/collection-immutability-update-example.log[]</code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
<div class="paragraph">
<p>While immutable entity changes are simply discarded, modifying an immutable collection end up in a <code>HibernateException</code> being thrown.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2017-02-16 12:14:38 +01:00
</div>
</div>
</body>
</html>